Sum of leaf nodes at minimum level

Given a binary tree containing n nodes. The problem is to get the sum of all the leaf nodes which are at minimum level in the binary tree.

Examples:

Input : 
              1
            /   \
           2     3
         /  \   /  \
        4   5   6   7
           /     \
          8       9

Output : 11
Leaf nodes 4 and 7 are at minimum level.
Their sum = (4 + 7) = 11. 

Source: Microsoft IDC Interview Experience | Set 150.



Approach: Perform iterative level order traversal using queue and find the first level containing a leaf node. Sum up all the leaf nodes at this level and then stop performing the traversal further.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the sum of
// leaf nodes at minimum level
#include <bits/stdc++.h>
using namespace std;
  
// structure of a node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
  
// function to get a new node
Node* getNode(int data)
{
    // allocate space
    Node* newNode = (Node*)malloc(sizeof(Node));
  
    // put in the data
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
  
// function to find the sum of
// leaf nodes at minimum level
int sumOfLeafNodesAtMinLevel(Node* root)
{
    // if tree is empty
    if (!root)
        return 0;
  
    // if there is only one node
    if (!root->left && !root->right)
        return root->data;
  
    // queue used for level order traversal
    queue<Node*> q;
    int sum = 0; 
    bool f = 0;
  
    // push root node in the queue 'q'
    q.push(root);
  
    while (f == 0) {
  
        // count number of nodes in the
        // current level
        int nc = q.size();
  
        // traverse the current level nodes
        while (nc--) {
  
            // get front element from 'q'
            Node* top = q.front();
            q.pop();
  
            // if it is a leaf node
            if (!top->left && !top->right) {
  
                // accumulate data to 'sum'
                sum += top->data;
  
                // set flag 'f' to 1, to signify 
                // minimum level for leaf nodes 
                // has been encountered
                f = 1;
            }
            else {
  
                // if top's left and right child 
                // exists, then push them to 'q'
                if (top->left)
                    q.push(top->left);
                if (top->right)
                    q.push(top->right);
            }
        }
    }
  
    // required sum
    return sum;
}
  
// Driver program to test above
int main()
{
    // binary tree creation
    Node* root = getNode(1);
    root->left = getNode(2);
    root->right = getNode(3);
    root->left->left = getNode(4);
    root->left->right = getNode(5);
    root->right->left = getNode(6);
    root->right->right = getNode(7);
    root->left->right->left = getNode(8);
    root->right->left->right = getNode(9);
  
    cout << "Sum = "
         << sumOfLeafNodesAtMinLevel(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the sum of
// leaf nodes at minimum level
import java.util.*;
  
class GFG 
{
  
// structure of a node of binary tree
static class Node 
{
    int data;
    Node left, right;
};
  
// function to get a new node
static Node getNode(int data)
{
    // allocate space
    Node newNode = new Node();
  
    // put in the data
    newNode.data = data;
    newNode.left = newNode.right = null;
    return newNode;
}
  
// function to find the sum of
// leaf nodes at minimum level
static int sumOfLeafNodesAtMinLevel(Node root)
{
    // if tree is empty
    if (root == null)
        return 0;
  
    // if there is only one node
    if (root.left == null &&
        root.right == null)
        return root.data;
  
    // queue used for level order traversal
    Queue<Node> q = new LinkedList<>();
    int sum = 0
    boolean f = false;
  
    // push root node in the queue 'q'
    q.add(root);
  
    while (f == false)
    {
  
        // count number of nodes in the
        // current level
        int nc = q.size();
  
        // traverse the current level nodes
        while (nc-- >0)
        {
  
            // get front element from 'q'
            Node top = q.peek();
            q.remove();
  
            // if it is a leaf node
            if (top.left == null && 
                top.right == null
            {
  
                // accumulate data to 'sum'
                sum += top.data;
  
                // set flag 'f' to 1, to signify 
                // minimum level for leaf nodes 
                // has been encountered
                f = true;
            }
            else 
            {
  
                // if top's left and right child 
                // exists, then push them to 'q'
                if (top.left != null)
                    q.add(top.left);
                if (top.right != null)
                    q.add(top.right);
            }
        }
    }
  
    // required sum
    return sum;
}
  
// Driver Code
public static void main(String[] args)
{
      
    // binary tree creation
    Node root = getNode(1);
    root.left = getNode(2);
    root.right = getNode(3);
    root.left.left = getNode(4);
    root.left.right = getNode(5);
    root.right.left = getNode(6);
    root.right.right = getNode(7);
    root.left.right.left = getNode(8);
    root.right.left.right = getNode(9);
  
    System.out.println("Sum = "
           sumOfLeafNodesAtMinLevel(root));
    }
}
  
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the sum of
// leaf nodes at minimum level
using System;
using System.Collections.Generic;
  
class GFG 
{
  
// structure of a node of binary tree
class Node 
{
    public int data;
    public Node left, right;
};
  
// function to get a new node
static Node getNode(int data)
{
    // allocate space
    Node newNode = new Node();
  
    // put in the data
    newNode.data = data;
    newNode.left = newNode.right = null;
    return newNode;
}
  
// function to find the sum of
// leaf nodes at minimum level
static int sumOfLeafNodesAtMinLevel(Node root)
{
    // if tree is empty
    if (root == null)
        return 0;
  
    // if there is only one node
    if (root.left == null &&
        root.right == null)
        return root.data;
  
    // queue used for level order traversal
    Queue<Node> q = new Queue<Node>();
    int sum = 0; 
    bool f = false;
  
    // push root node in the queue 'q'
    q.Enqueue(root);
  
    while (f == false)
    {
  
        // count number of nodes in the
        // current level
        int nc = q.Count;
  
        // traverse the current level nodes
        while (nc-- >0)
        {
  
            // get front element from 'q'
            Node top = q.Peek();
            q.Dequeue();
  
            // if it is a leaf node
            if (top.left == null && 
                top.right == null
            {
  
                // accumulate data to 'sum'
                sum += top.data;
  
                // set flag 'f' to 1, to signify 
                // minimum level for leaf nodes 
                // has been encountered
                f = true;
            }
            else
            {
  
                // if top's left and right child 
                // exists, then push them to 'q'
                if (top.left != null)
                    q.Enqueue(top.left);
                if (top.right != null)
                    q.Enqueue(top.right);
            }
        }
    }
  
    // required sum
    return sum;
}
  
// Driver Code
public static void Main(String[] args)
{
      
    // binary tree creation
    Node root = getNode(1);
    root.left = getNode(2);
    root.right = getNode(3);
    root.left.left = getNode(4);
    root.left.right = getNode(5);
    root.right.left = getNode(6);
    root.right.right = getNode(7);
    root.left.right.left = getNode(8);
    root.right.left.right = getNode(9);
  
    Console.WriteLine("Sum = "
            sumOfLeafNodesAtMinLevel(root));
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

Sum = 11

Time Complexity: O(n).
Auxiliary Space: O(n).



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Rajput-Ji, princiraj1992