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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* getNode( int data)
{
Node* newNode = (Node*) malloc ( sizeof (Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
int sumOfLeafNodesAtMinLevel(Node* root)
{
if (!root)
return 0;
if (!root->left && !root->right)
return root->data;
queue<Node*> q;
int sum = 0;
bool f = 0;
q.push(root);
while (f == 0) {
int nc = q.size();
while (nc--) {
Node* top = q.front();
q.pop();
if (!top->left && !top->right) {
sum += top->data;
f = 1;
}
else {
if (top->left)
q.push(top->left);
if (top->right)
q.push(top->right);
}
}
}
return sum;
}
int main()
{
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;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left, right;
};
static Node getNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return newNode;
}
static int sumOfLeafNodesAtMinLevel(Node root)
{
if (root == null )
return 0 ;
if (root.left == null &&
root.right == null )
return root.data;
Queue<Node> q = new LinkedList<>();
int sum = 0 ;
boolean f = false ;
q.add(root);
while (f == false )
{
int nc = q.size();
while (nc-- > 0 )
{
Node top = q.peek();
q.remove();
if (top.left == null &&
top.right == null )
{
sum += top.data;
f = true ;
}
else
{
if (top.left != null )
q.add(top.left);
if (top.right != null )
q.add(top.right);
}
}
}
return sum;
}
public static void main(String[] args)
{
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));
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def sumOfLeafNodesAtLeafLevel(root):
if not root:
return 0
if not root.left and not root.right:
return root.data
Queue = deque()
sum = f = 0
Queue.append(root)
while not f:
nc = len (Queue)
while nc:
top = Queue.popleft()
if not top.left and not top.right:
sum + = top.data
f = 1
else :
if top.left:
Queue.append(top.left)
if top.right:
Queue.append(top.right)
nc - = 1
return sum
if __name__ = = "__main__" :
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.right.left = Node( 6 )
root.right.right = Node( 7 )
root.left.right.left = Node( 8 )
root.right.left.right = Node( 9 )
print ( "Sum = " , sumOfLeafNodesAtLeafLevel(root))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int data;
public Node left, right;
};
static Node getNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return newNode;
}
static int sumOfLeafNodesAtMinLevel(Node root)
{
if (root == null )
return 0;
if (root.left == null &&
root.right == null )
return root.data;
Queue<Node> q = new Queue<Node>();
int sum = 0;
bool f = false ;
q.Enqueue(root);
while (f == false )
{
int nc = q.Count;
while (nc-- >0)
{
Node top = q.Peek();
q.Dequeue();
if (top.left == null &&
top.right == null )
{
sum += top.data;
f = true ;
}
else
{
if (top.left != null )
q.Enqueue(top.left);
if (top.right != null )
q.Enqueue(top.right);
}
}
}
return sum;
}
public static void Main(String[] args)
{
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));
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function getNode(data)
{
let newNode = new Node(data);
return newNode;
}
function sumOfLeafNodesAtMinLevel(root)
{
if (root == null )
return 0;
if (root.left == null &&
root.right == null )
return root.data;
let q = [];
let sum = 0;
let f = false ;
q.push(root);
while (f == false )
{
let nc = q.length;
while (nc-- >0)
{
let top = q[0];
q.shift();
if (top.left == null &&
top.right == null )
{
sum += top.data;
f = true ;
}
else
{
if (top.left != null )
q.push(top.left);
if (top.right != null )
q.push(top.right);
}
}
}
return sum;
}
let 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);
document.write( "Sum = " +
sumOfLeafNodesAtMinLevel(root));
</script>
|
Time Complexity: O(n).
Auxiliary Space: O(n).
Another Method using Recursion
Here we will use the concept of traversal of a binary tree. In the function call, will take the root node and level variable, for tracking the levels of every node, also we will be using a hash-map, whose key is our value of level and the other as a vector for storing the node’s data for that particular node . For every recursive call, we will increase the level variable, and if the current node is a leaf node then we will push into a map with the key as level and node’s data into a vector. Once we get our map, will simply sum the vector of very first element of our map;
Implementation: Let’s see the code once, and your every confusion will be gone.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* getNode( int data)
{
Node* newNode = (Node*) malloc ( sizeof (Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
map < int , vector < int >> mp;
void solve(Node* root, int level) {
if (root == NULL)
return ;
if (root->left == NULL && root->right == NULL)
mp[level].push_back(root->data);
solve(root->left, level+1);
solve(root->right, level+1);
}
int minLeafSum(Node *root)
{
solve(root, 0);
int sum = 0;
for ( auto i:mp) {
for ( auto j:i.second) {
sum += j;
}
return sum;
}
}
int main() {
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);
cout << "Sum = " << minLeafSum(root);
return 0;
}
|
Java
import java.util.TreeMap;
import java.util.Vector;
import java.util.Map.Entry;
class GFG {
static class Node {
int data;
Node left, right;
};
static Node getNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return newNode;
}
static TreeMap<Integer, Vector <Integer>> mp = new TreeMap <Integer, Vector <Integer>>();
static void solve(Node root, int level) {
if (root == null )
return ;
if (root.left == null && root.right == null )
{
Vector<Integer> get = mp.get(level);
if (get == null )
{
get = new Vector<>();
get.add(root.data);
}
else
get.add(root.data);
mp.put(level, get);
}
solve(root.left, level+ 1 );
solve(root.right, level+ 1 );
}
static int minLeafSum(Node root)
{
solve(root, 0 );
int sum = 0 ;
for (Entry<Integer, Vector<Integer>> i : mp.entrySet())
{
for (Integer j : i.getValue())
{
sum+=j;
}
return sum;
}
return 0 ;
}
public static void main(String[] args)
{
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 );
System.out.println(
"Sum = " + minLeafSum(root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
mp = dict ()
def solve(root,level):
if (root = = None ):
return
if root.left = = None and root.right = = None :
try :
mp[level].append(root.data)
except :
mp[level] = [root.data]
solve(root.left, level + 1 )
solve(root.right, level + 1 )
def minLeafSum(root):
solve(root, 0 )
sum = 0
for x, i in enumerate ( sorted (mp)):
for j in mp[i]:
sum + = j
return sum
if __name__ = = "__main__" :
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.right.left = Node( 6 )
root.right.right = Node( 7 )
print ( "Sum = " , minLeafSum(root))
|
C#
using System;
using System.Collections.Generic;
class GFG {
class Node {
public int data;
public Node left, right;
};
static Node getNode( int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = newNode.right = null ;
return newNode;
}
static SortedDictionary< int , List< int > > mp
= new SortedDictionary< int , List< int > >();
static void solve(Node root, int level)
{
if (root == null )
return ;
if (root.left == null && root.right == null ) {
List< int > get = new List< int >();
if (mp.ContainsKey(level))
get .AddRange(mp[level]);
if ( get == null ) {
get = new List< int >();
get .Add(root.data);
}
else
get .Add(root.data);
mp[level] = get ;
}
solve(root.left, level + 1);
solve(root.right, level + 1);
}
static int minLeafSum(Node root)
{
solve(root, 0);
int sum = 0;
foreach (KeyValuePair< int , List< int > > i in mp)
{
foreach ( int j in i.Value) sum += j;
return sum;
}
return 0;
}
public static void Main(String[] args)
{
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);
Console.WriteLine( "Sum = " + minLeafSum(root));
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function getNode(data) {
let newNode = new Node(data);
return newNode;
}
let mp = new Map();
function solve(root, level) {
if (root == null )
return ;
if (root.left == null && root.right == null )
mp.has(level) ? mp.get(level).push(root.data) : mp.set(level, [root.data]);
solve(root.left, level + 1);
solve(root.right, level + 1);
}
function minLeafSum(root) {
solve(root, 0);
let sum = 0;
for (const [key, value] of mp.entries()) {
for (let j = 0; j < value.length; j++) {
sum += value[j];
}
return sum;
}
}
let 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);
console.log( "Sum = " + minLeafSum(root));
|
Time Complexity: O(n) where n is the number of nodes in the tree.
Auxiliary Space: O(h) where h is the height of the binary tree.