计算指定节点*p所在的层数

来源:互联网 发布:cnc刀库编程 编辑:程序博客网 时间:2024/05/17 22:09

计算二叉树指定结点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}

参考资料

https://zhidao.baidu.com/question/417870986.html

原创粉丝点击