二叉树-递归计算某节点的层数/深度

该函数需要传入某已知节点、该节点的depth/level和目标节点,将返回目标节点的depth/level
目标节点在已知节点的子树中才可以,通常传入整个树,如下

	level = Rec_GetLevel(t, 1, target);
#include <stdio.h>
#include <stdlib.h>
#define NOT_FOUND -999
typedef struct node{ 
	int Element;
	struct node* Left;
	struct node* Right;
}Node;

int Rec_GetLevel(Node* base_node, int base_level, Node* target)
{ 
	if (base_node == NULL)return NOT_FOUND;
	if (target == base_node)return base_level;
	
	int level_from_left, level_from_right;

	level_from_left = Rec_GetLevel(base_node->Left, base_level + 1, target);
	if (level_from_left != NOT_FOUND)return level_from_left;
	
	level_from_right = Rec_GetLevel(base_node->Right, base_level + 1, target);
	if (level_from_right != NOT_FOUND)return level_from_right;
	
	return NOT_FOUND;
}
    原文作者:SydneyCarton_
    原文地址: https://blog.csdn.net/SydneyCarton_/article/details/109071437
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞