【发布时间】:2021-01-30 15:53:15
【问题描述】:
假设以下树按顺序排列:2、9、4、7。我需要找到每个节点的深度:节点 2 - 深度 0,节点 9 - 深度 1,节点 4 - 深度 2,节点 7 - 深度 3 .
2
\
9
/
4
\
7
但是,我得到的输出是:节点 2 - 深度 0,节点 9 - 深度 -1,节点 4 - 深度 -1,节点 7 - 深度 -1。
我认为我无法遍历右子树,因为 left 每次都大于零,并且函数在到达右侧之前退出。但我不确定如何修复代码以产生正确的输出。
我的代码:
int findDepth(Tree t, int key, int depth) {
if (t == NULL) {
return -1;
}
if (t->value == key) {
return depth;
}
int left = findDepth(t->left, key, depth + 1);
if (left != 0) {
return left;
}
int right = findDepth(t->right, key, depth + 1);
if (right != 0) {
return right;
}
return 0;
}
int treeNodeDepth(Tree t, int key) {
return findDepth(t, key, 0);
}
【问题讨论】:
标签: c