二进制搜索树的最大深度
Max depth of Binary search tree
我想找到二进制搜索树的最大深度。我找到了一个代码。
int maxDepth(struct node* node) {
if (node==NULL) {
return(0);
}
else {
// compute the depth of each subtree
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
// use the larger one
if (lDepth > rDepth) return(lDepth+1);
else return(rDepth+1);
}
}
我想知道node->left怎么会返回1?
它是默认的吗?代码很简单,但我不知道从哪里来的答案,有人能解释一下吗?
给定此树:
[A]
/\
[B] [C]
对于带有NULL的[B]和带有NULL的[C],将调用maxDepth,两者都返回零,因此递归调用最终返回0+1。
如果在[C]下有一个节点[D],那么对[D]maxDepth的调用将返回NULL,D将返回0+1,然后递归将继续按比例放大,[C]将接收0+1,并返回一些+1,返回的maxDepth为2,它大于持有[B]的分支的深度,即1,因此maxDepth 2从完整递归中返回。
当node
指向一个叶时,它的node->left
和node->right
都是NULL
。所以maxDepth()
都返回0
。因此,该叶的当前递归只返回深度为0 + 1 = 1.
的
你可以证明它的正确性。
初始化
当节点为NULL
时,返回0
。的确,一棵空树的深度为0
。当节点是叶子时,它返回1
。正如刚才所解释的。
维护
如果存在一个节点(不是NULL
),并且我们知道其子节点的深度,则该节点的深度将是max(depth of left, depth of right) + 1
。这就是回报。
终止
它将终止,因为当它到达叶时,递归将停止变得更深并返回。当整个递归结束时,maxDepth(root)
返回root
的深度。
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 深度复制和取消引用
- C++二叉搜索树打印和深度计算
- 显示属于二叉搜索树深度路径的节点
- 深度优先搜索树遍历实现在C++
- 深度优先搜索树边分类
- 二叉搜索树的深度
- 二进制搜索树的最大深度