简体   繁体   English

查找二叉树中最深叶节点的总和?

[英]Finding sum of only deepest leaf nodes in the binary tree?

I was solving a question given above and deepest meant only the leaf nodes which are at level = height of the tree.我正在解决上面给出的一个问题,最深的意思是只有位于树的高度 = 高度的叶节点。 I solved it through an approach which is giving wrong output and i cannot find why while debugging it.我通过一种给出错误输出的方法解决了它,我在调试时找不到原因。

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;

The main function here is deepestLeavesSum.这里的主要函数是 deepestLeavesSum。 The output i am getting is 0 for all the test cases对于所有测试用例,我得到的输出都是 0

well, well, well..嗯嗯嗯嗯..

the problem lies in method where you calculating height.问题在于你计算高度的方法。 your "height" method needs this modification.您的“高度”方法需要进行此修改。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM