Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在二叉树中只查找最深叶节点的和?_C++_Recursion_Binary Tree - Fatal编程技术网

C++ 在二叉树中只查找最深叶节点的和?

C++ 在二叉树中只查找最深叶节点的和?,c++,recursion,binary-tree,C++,Recursion,Binary Tree,我在解决上面给出的一个问题,最深的意思是只在树的level=高度处的叶节点。我通过一种给出错误输出的方法解决了这个问题,但在调试时我找不到原因 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) {

我在解决上面给出的一个问题,最深的意思是只在树的level=高度处的叶节点。我通过一种给出错误输出的方法解决了这个问题,但在调试时我找不到原因

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

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

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

谢谢你的建议,但我想这就是我在上面代码中所做的。使用的语言是C++,非常感谢。这是我这边的一个很糟糕的错误,很多天来我都无法调查这一点。