[英]Finding sum of only deepest leaf nodes in the binary tree?
我正在解決上面給出的一個問題,最深的意思是只有位於樹的高度 = 高度的葉節點。 我通過一種給出錯誤輸出的方法解決了它,我在調試時找不到原因。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.