试图找到二叉树的深度
Trying to find depth of binary tree
我正在尝试编写一些东西来确定二叉树的最大深度,但到目前为止,最终只有一件事不断返回树中的节点数,而另一件事,在下面,总是或多或少地偏离。经过几个小时的尝试调整,我真的可以使用一些建议。
void findthedepth(nodeoftree<node>* root, int* depthtotal, int* depthcurrent){
int left = 0, right = 0;
if( root == nullptr ){
*depthtotal = 0;
*depthcurrent = 0;
return;
}
findthedepth(root->rightp(), depthtotal, depthcurrent);
right = *depthcurrent;
*depthcurrent = 0;
findthedepth(root->leftp(), depthtotal, depthcurrent);
left = *depthcurrent;
if (left > right){
*depthtotal += left + 1;
}
else {
*depthtotal += right + 1;
}
}
有两种情况需要考虑:
- 一棵空树的深度为零; 非空树的深度
- 比其两个子树的深度高一级,因此它具有深度
1 + max(depth_left, depth_right)
。
如果我们用C++写出来:
int depth(nodeoftree<node>* root) {
if (root == nullptr)
return 0;
int depth_left = depth(node->leftp());
int depth_right = depth(node->rightp());
return 1 + max(depth_left, depth_right);
}
你离得很近,你不需要depthCurrent
指针
findthedepth(root->rightp(), depthtotal /*, depthcurrent*/);
right = *depthtotal; // update the total depth captured in right
// *depthcurrent = 0; (no use)
findthedepth(root->leftp(), depthtotal /*, depthcurrent*/);
left = *depthtotal; // update the total depth captured in left
相关文章:
- 从父数组测试用例构造二叉树失败
- 打印时有二叉树问题.用户输入不打印任何内容
- 试图找到二叉树的深度
- 二叉树结构平衡,使用递归时EXC_BAD_ACCESS
- 指向二叉树中新节点的指针
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- C++:如何计算二叉树中其值模块高度小于 2 的节点数?
- 二叉树级别顺序遍历在leetcode中
- 运行无限循环的最小二叉树问题
- 打印二叉树中的常见元素
- 二叉树基准测试结果
- 带有矢量重复值的二叉树打印出来
- 签入二叉树的函数是平衡C++
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 如何计算给定数字在二叉树中出现的次数?
- 为什么我的二叉树会覆盖其根的叶子?
- 查找二叉树中特定节点的深度
- 给定一个二叉树,设计一个算法,创建每个深度的所有节点的链表
- 二叉树的深度复制
- 二叉树中节点的深度