Abhijeet Ashok Muneshwar
Abhijeet Ashok Muneshwar

Reputation: 2508

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:

Binary Tree

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

(Image Source: GeeksForGeeks)

Upvotes: 2

Views: 2045

Answers (2)

Ayush Pallav
Ayush Pallav

Reputation: 1057

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 ;
}

Upvotes: 0

Ivan Gritsenko
Ivan Gritsenko

Reputation: 4236

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.

Upvotes: 4

Related Questions