[英]Sum of all leaf nodes at minimum level in binary tree
How to calculate sum of all the leaf nodes at minimum level in a binary tree. 如何在二叉树中以最小级别计算所有叶节点的总和。 If there exists no tree, then it should return -1. 如果不存在树,则应返回-1。
Example: 例:
For the above binary tree, return 100 (40+60) 对于上述二叉树,返回100(40 + 60)
(Image Source: GeeksForGeeks ) (图片来源: GeeksForGeeks )
f(node, level):
if node is null then
return { Inf, -1 }
if isLeaf(node) then
return { level, node.value }
fleft <- f(node.left, level + 1)
fright <- f(node.right, level + 1)
fnode <- { min(fleft.first, fright.first), 0 }
if fnode.first = fleft.first then
fnode.second <- fnode.second + fleft.second
if fnode.first = fright.first then
fnode.second <- fnode.second + fright.second
return fnode
A function returns a pair of values where first
is a minimum leaf level and second
is the sum of the leaf elements on this level. 函数返回一对值,其中first
是最小叶子级别, second
是该级别上叶子元素的总和。
You can use map as well, minLeafSum
is the driving function, logic is simple. 您也可以使用地图, minLeafSum
是驱动函数,逻辑很简单。 Just go through the code. 只需检查代码即可。
void getmin(map<int,vector<int>> &m,Node* root,int level)
{
if(root==NULL)
return;
if(root->left==NULL && root->right==NULL)
{
m[level].push_back(root->data);
return;
}
if(root->left!=NULL)
getmin(m,root->left,level+1);
if(root->right!=NULL)
getmin(m,root->right,level+1);
}
int minLeafSum(Node* root)
{
int ans=0;
map<int,vector<int>> m;
getmin(m,root,0);
auto it = m.begin();
for(int i=0; i< it->second.size() ;i++)
ans += it->second[i];
return ans ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.