计算二叉树指定结点p的层数(设树根为第一层
假设二叉树采用链表存储结构,请设计一个函数 int level(struct node *t,struct *p) 求二叉树t中指定结点p的层数(设树根为第一层)。说明:若树t为空,则返回0;若p不在t中返回-1,允许自行设计函数供level调用。
strut node{
int info;
struct node *left;
struct node *right;
}
int level(struct node *t,struct *p)
{
……
}
算法设计如下
//递归查找,找到后返回层数depth
int level(struct node *t,struct node *p) {
return t ? _level(t, p, 1) : 0;
}
int __level(struct node *cur, struct node *goal, int depth) {
if (cur == NULL) return 0;
if (cur == goal) return depth;
int l = __level(cur->left, goal, depth + 1);
if (l > 0) return l;
int r = __level(cur->right, goal, depth + 1);
if (r > 0) return r;
return -1
}
————————————————
版权声明:本文为CSDN博主「寒江雪江南岸蓑笠翁」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u013592116/article/details/73459741