简体   繁体   中英

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.

Example:

二叉树

For the above binary tree, return 100 (40+60)

(Image Source: 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.

You can use map as well, minLeafSum is the driving function, logic is simple. 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 ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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