【问题标题】:Trying to find depth of binary tree试图找到二叉树的深度
【发布时间】: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-&gt;rightp(), &amp;right) 来修复您的递归调用(左侧类似)。您最后写给depthtotal 是正确的。绝对切换到直接返回一个值或将 referencedepthcurrent.

标签: c++ binary-tree


【解决方案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);
}

【讨论】:

    【解决方案2】:

    你很亲密,你不需要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
    

    【讨论】:

      猜你喜欢
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2014-08-07
      相关资源
      最近更新 更多