【发布时间】:2020-02-04 23:23:35
【问题描述】:
我正在尝试写一些东西来确定二叉树的最大深度,但到目前为止只有一个东西会不断返回树中的节点数,而另一个东西,在下面,总是多一个或更少关闭。经过数小时的尝试调整后,我真的可以使用一些建议..
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;
}
}
【问题讨论】:
-
我建议删除这些指针,然后简单地返回值。它使代码更易于阅读,并且可能更容易找到问题。
-
在非空的情况下,您似乎从未真正写信给
depthcurrent,所以摆脱它。然后,您可以通过执行findthedepth(root->rightp(), &right)来修复您的递归调用(左侧类似)。您最后写给depthtotal是正确的。绝对切换到直接返回一个值或将 reference 到depthcurrent.
标签: c++ binary-tree