c++ - 试图找到二叉树的深度
问题描述
我正在尝试编写一些东西来确定二叉树的最大深度,但到目前为止,只有一件事情会不断返回树中的节点数,而另一件事情,在下面,总是或多或少. 经过数小时的尝试调整后,我真的可以使用一些建议..
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;
}
}
解决方案
有两种情况需要考虑:
- 一棵空树的深度为零;
- 一棵非空树比它的两个子树的深度多一层,所以它有 depth
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);
}
推荐阅读
- multithreading - 如果并发线程数为 10 且 SysTick 时间为 10mSec,则 1 个线程执行时间(量子)是多少?
- java - 如何在 RHEL RedHatLinux 机器上验证哪个 openjdk 发行版供应商?
- jquery - 在rails条件中使用js变量
- java - 鼠标滚轮上的水平滚动不适用于 RecyclerView Android
- vb.net - Option Strict On 不允许在 vb.net 中进行后期绑定
- javascript - 如何在后端 express 函数中访问当前 url 中的参数?(见说明)
- android-studio - 当我运行我的项目时,为什么会出现这个错误?
- typescript - 在 Angular 6 中集成 Stripe 支付网关时面临“需要卡”错误
- hdfs - HA namenode config的hdfs上的Flink检查点
- node.js - 这是在 docker 容器内的 node.js 和云问题上运行的通用 expressjs