【问题标题】:Finding sum of only deepest leaf nodes in the binary tree?仅查找二叉树中最深叶节点的总和?
【发布时间】:2021-02-19 19:47:09
【问题描述】:

我正在解决上面给出的一个问题,最深意味着只有叶节点位于树的级别 = 高度。我通过一种给出错误输出的方法解决了它,我在调试时找不到原因。

int deepsum(TreeNode* root,int h,int sum,int l)
    {
        if(root==NULL)
            return 0;
        if(l==h and root->left==NULL and root->right==NULL)
        {
            sum=root->val;
            return sum;
        }
        int lss=deepsum(root->left,h,sum,l+1);
        int rss=deepsum(root->right,h,sum,l+1);
        return lss+rss;
    }
    int height(TreeNode* root)
    {
         if(root==NULL)
            return 0;
        int ls=deepestLeavesSum(root->left);
        int rs=deepestLeavesSum(root->right);
        return max(ls,rs)+1;
    }
    int deepestLeavesSum(TreeNode* root) {
       int h=height(root);
        int new_sum=deepsum(root,h,0,1);
        return new_sum;

这里的主要函数是 deepestLeavesSum。对于所有测试用例,我得到的输出都是 0

【问题讨论】:

  • 感谢您的建议,但我认为这就是我在上面的代码中所做的。使用的语言是 C++。

标签: c++ recursion binary-tree


【解决方案1】:

好吧,好吧,好吧..

问题在于计算高度的方法。您的“高度”方法需要进行此修改。

 int height(TreeNode* root)
{
     if(root==NULL)
        return 0;
    int ls=height(root->left); // 
    int rs=height(root->right);
    return max(ls,rs)+1;
}

【讨论】:

  • 非常感谢。从我的角度来看,这是一个非常糟糕的错误,这么多​​天我都无法调查。
猜你喜欢
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
相关资源
最近更新 更多