Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6.

The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then add it to the result.
Following is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node* left, *right;
};
Node *newNode( char k)
{
Node *node = new Node;
node->key = k;
node->right = node->left = NULL;
return node;
}
bool isLeaf(Node *node)
{
if (node == NULL)
return false ;
if (node->left == NULL && node->right == NULL)
return true ;
return false ;
}
int leftLeavesSum(Node *root)
{
int res = 0;
if (root != NULL)
{
if (isLeaf(root->left))
res += root->left->key;
else
res += leftLeavesSum(root->left);
res += leftLeavesSum(root->right);
}
return res;
}
int main()
{
struct Node *root = newNode(20);
root->left = newNode(9);
root->right = newNode(49);
root->right->left = newNode(23);
root->right->right = newNode(52);
root->right->right->left = newNode(50);
root->left->left = newNode(5);
root->left->right = newNode(12);
root->left->right->right = newNode(12);
cout << "Sum of left leaves is "
<< leftLeavesSum(root);
return 0;
}
|
Java
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree
{
Node root;
boolean isLeaf(Node node)
{
if (node == null )
return false ;
if (node.left == null && node.right == null )
return true ;
return false ;
}
int leftLeavesSum(Node node)
{
int res = 0 ;
if (node != null )
{
if (isLeaf(node.left))
res += node.left.data;
else
res += leftLeavesSum(node.left);
res += leftLeavesSum(node.right);
}
return res;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 20 );
tree.root.left = new Node( 9 );
tree.root.right = new Node( 49 );
tree.root.left.right = new Node( 12 );
tree.root.left.left = new Node( 5 );
tree.root.right.left = new Node( 23 );
tree.root.right.right = new Node( 52 );
tree.root.left.right.right = new Node( 12 );
tree.root.right.right.left = new Node( 50 );
System.out.println( "The sum of leaves is " +
tree.leftLeavesSum(tree.root));
}
}
|
Python
class Node:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def isLeaf(node):
if node is None :
return False
if node.left is None and node.right is None :
return True
return False
def leftLeavesSum(root):
res = 0
if root is not None :
if isLeaf(root.left):
res + = root.left.key
else :
res + = leftLeavesSum(root.left)
res + = leftLeavesSum(root.right)
return res
root = Node( 20 )
root.left = Node( 9 )
root.right = Node( 49 )
root.right.left = Node( 23 )
root.right.right = Node( 52 )
root.right.right.left = Node( 50 )
root.left.left = Node( 5 )
root.left.right = Node( 12 )
root.left.right.right = Node( 12 )
print "Sum of left leaves is" , leftLeavesSum(root)
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree
{
public Node root;
public virtual bool isLeaf(Node node)
{
if (node == null )
{
return false ;
}
if (node.left == null && node.right == null )
{
return true ;
}
return false ;
}
public virtual int leftLeavesSum(Node node)
{
int res = 0;
if (node != null )
{
if (isLeaf(node.left))
{
res += node.left.data;
}
else
{
res += leftLeavesSum(node.left);
}
res += leftLeavesSum(node.right);
}
return res;
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(9);
tree.root.right = new Node(49);
tree.root.left.right = new Node(12);
tree.root.left.left = new Node(5);
tree.root.right.left = new Node(23);
tree.root.right.right = new Node(52);
tree.root.left.right.right = new Node(12);
tree.root.right.right.left = new Node(50);
Console.WriteLine( "The sum of leaves is " + tree.leftLeavesSum(tree.root));
}
}
|
Output
Sum of left leaves is 78
Time Complexity: O(N), where n is number of nodes in Binary Tree.
Following is Another Method to solve the above problem. This solution passes in a sum variable as an accumulator. When a left leaf is encountered, the leaf’s data is added to sum. Time complexity of this method is also O(n). Thanks to Xin Tong (geeksforgeeks userid trent.tong) for suggesting this method.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node* left, *right;
};
Node *newNode( char k)
{
Node *node = new Node;
node->key = k;
node->right = node->left = NULL;
return node;
}
void leftLeavesSumRec(Node *root, bool isleft, int *sum)
{
if (!root) return ;
if (!root->left && !root->right && isleft)
*sum += root->key;
leftLeavesSumRec(root->left, 1, sum);
leftLeavesSumRec(root->right, 0, sum);
}
int leftLeavesSum(Node *root)
{
int sum = 0;
leftLeavesSumRec(root, 0, &sum);
return sum;
}
int main()
{
int sum = 0;
struct Node *root = newNode(20);
root->left = newNode(9);
root->right = newNode(49);
root->right->left = newNode(23);
root->right->right = newNode(52);
root->right->right->left = newNode(50);
root->left->left = newNode(5);
root->left->right = newNode(12);
root->left->right->right = newNode(12);
cout << "Sum of left leaves is "
<< leftLeavesSum(root) << endl;
return 0;
}
|
Java
class Node
{
int data;
Node left, right;
Node( int item) {
data = item;
left = right = null ;
}
}
class Sum
{
int sum = 0 ;
}
class BinaryTree
{
Node root;
void leftLeavesSumRec(Node node, boolean isleft, Sum summ)
{
if (node == null )
return ;
if (node.left == null && node.right == null && isleft)
summ.sum = summ.sum + node.data;
leftLeavesSumRec(node.left, true , summ);
leftLeavesSumRec(node.right, false , summ);
}
int leftLeavesSum(Node node)
{
Sum suum = new Sum();
leftLeavesSumRec(node, false , suum);
return suum.sum;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 20 );
tree.root.left = new Node( 9 );
tree.root.right = new Node( 49 );
tree.root.left.right = new Node( 12 );
tree.root.left.left = new Node( 5 );
tree.root.right.left = new Node( 23 );
tree.root.right.right = new Node( 52 );
tree.root.left.right.right = new Node( 12 );
tree.root.right.right.left = new Node( 50 );
System.out.println( "The sum of leaves is " +
tree.leftLeavesSum(tree.root));
}
}
|
Python
class Node:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def leftLeavesSumRec(root, isLeft, summ):
if root is None :
return
if root.left is None and root.right is None and isLeft = = True :
summ[ 0 ] + = root.key
leftLeavesSumRec(root.left, 1 , summ)
leftLeavesSumRec(root.right, 0 , summ)
def leftLeavesSum(root):
summ = [ 0 ]
leftLeavesSumRec(root, 0 , summ)
return summ[ 0 ]
root = Node( 20 );
root.left = Node( 9 );
root.right = Node( 49 );
root.right.left = Node( 23 );
root.right.right = Node( 52 );
root.right.right.left = Node( 50 );
root.left.left = Node( 5 );
root.left.right = Node( 12 );
root.left.right.right = Node( 12 );
print "Sum of left leaves is" , leftLeavesSum(root)
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class Sum
{
public int sum = 0;
}
public class BinaryTree
{
public Node root;
public virtual void leftLeavesSumRec(Node node, bool isleft, Sum summ)
{
if (node == null )
{
return ;
}
if (node.left == null && node.right == null && isleft)
{
summ.sum = summ.sum + node.data;
}
leftLeavesSumRec(node.left, true , summ);
leftLeavesSumRec(node.right, false , summ);
}
public virtual int leftLeavesSum(Node node)
{
Sum suum = new Sum();
leftLeavesSumRec(node, false , suum);
return suum.sum;
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(9);
tree.root.right = new Node(49);
tree.root.left.right = new Node(12);
tree.root.left.left = new Node(5);
tree.root.right.left = new Node(23);
tree.root.right.right = new Node(52);
tree.root.left.right.right = new Node(12);
tree.root.right.right.left = new Node(50);
Console.WriteLine( "The sum of leaves is " + tree.leftLeavesSum(tree.root));
}
}
|
Output
Sum of left leaves is 78
Iterative Approach :
This is the Iterative Way to find the sum of the left leaves.
Idea is to perform Depth-First Traversal on the tree (either Inorder, Preorder or Postorder) using a stack and checking if the Left Child is a Leaf node. If it is, then add the nodes value to the sum variable
C++
#include<bits/stdc++.h>
using namespace std;
class Node
{
public :
int key;
Node* left, *right;
Node( int key_)
{
key = key_;
left = NULL;
right = NULL;
}
};
int sumOfLeftLeaves(Node* root)
{
if (root == NULL)
return 0;
stack<Node*> stack_;
stack_.push(root);
int sum = 0;
while (stack_.size() > 0)
{
Node* currentNode = stack_.top();
stack_.pop();
if (currentNode->left != NULL)
{
stack_.push(currentNode->left);
if (currentNode->left->left == NULL &&
currentNode->left->right == NULL)
{
sum = sum + currentNode->left->key ;
}
}
if (currentNode->right != NULL)
stack_.push(currentNode->right);
}
return sum;
}
int main()
{
Node *root = new Node(20);
root->left= new Node(9);
root->right = new Node(49);
root->right->left = new Node(23);
root->right->right= new Node(52);
root->right->right->left = new Node(50);
root->left->left = new Node(5);
root->left->right = new Node(12);
root->left->right->right = new Node(12);
cout << "Sum of left leaves is "
<< sumOfLeftLeaves(root) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int key;
Node left, right;
Node( int key_)
{
this .key = key_;
this .left = null ;
this .right = null ;
}
};
static int sumOfLeftLeaves(Node root)
{
if (root == null )
return 0 ;
Stack<Node> stack_ = new Stack<>();
stack_.push(root);
int sum = 0 ;
while (stack_.size() > 0 )
{
Node currentNode = stack_.peek();
stack_.pop();
if (currentNode.left != null )
{
stack_.add(currentNode.left);
if (currentNode.left.left == null &&
currentNode.left.right == null )
{
sum = sum + currentNode.left.key ;
}
}
if (currentNode.right != null )
stack_.add(currentNode.right);
}
return sum;
}
public static void main(String[] args)
{
Node root = new Node( 20 );
root.left= new Node( 9 );
root.right = new Node( 49 );
root.right.left = new Node( 23 );
root.right.right= new Node( 52 );
root.right.right.left = new Node( 50 );
root.left.left = new Node( 5 );
root.left.right = new Node( 12 );
root.left.right.right = new Node( 12 );
System.out.print( "Sum of left leaves is "
+ sumOfLeftLeaves(root) + "\n" );
}
}
|
Python3
class Node:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def sumOfLeftLeaves(root):
if (root is None ):
return
stack = []
stack.append(root)
sum = 0
while len (stack) > 0 :
currentNode = stack.pop()
if currentNode.left is not None :
stack.append(currentNode.left)
if currentNode.left.left is None and currentNode.left.right is None :
sum = sum + currentNode.left.data
if currentNode.right is not None :
stack.append(currentNode.right)
return sum
root = Tree( 20 );
root.left = Tree( 9 );
root.right = Tree( 49 );
root.right.left = Tree( 23 );
root.right.right = Tree( 52 );
root.right.right.left = Tree( 50 );
root.left.left = Tree( 5 );
root.left.right = Tree( 12 );
root.left.right.right = Tree( 12 );
print ( 'Sum of left leaves is {}' . format (sumOfLeftLeaves(root)))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public
class Node
{
public
int key;
public
Node left, right;
public
Node( int key_)
{
this .key = key_;
this .left = null ;
this .right = null ;
}
};
static int sumOfLeftLeaves(Node root)
{
if (root == null )
return 0;
Stack<Node> stack_ = new Stack<Node>();
stack_.Push(root);
int sum = 0;
while (stack_.Count > 0)
{
Node currentNode = stack_.Peek();
stack_.Pop();
if (currentNode.left != null )
{
stack_.Push(currentNode.left);
if (currentNode.left.left == null &&
currentNode.left.right == null )
{
sum = sum + currentNode.left.key ;
}
}
if (currentNode.right != null )
stack_.Push(currentNode.right);
}
return sum;
}
public static void Main(String[] args)
{
Node root = new Node(20);
root.left= new Node(9);
root.right = new Node(49);
root.right.left = new Node(23);
root.right.right= new Node(52);
root.right.right.left = new Node(50);
root.left.left = new Node(5);
root.left.right = new Node(12);
root.left.right.right = new Node(12);
Console.Write( "Sum of left leaves is "
+ sumOfLeftLeaves(root) + "\n" );
}
}
|
Output
Sum of left leaves is 78
Thanks to Shubham Tambere for suggesting this approach.
BFS Approach: We can do BFS traversal and keep a separate variable for denoting if it is a left child or right child of a node. As soon as we encounter a leaf, we check if it is a left child of its parent or right child of its parent. If it is a left child, we add its value in the sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int key;
Node *left, *right;
Node( int key_)
{
key = key_;
left = NULL;
right = NULL;
}
};
int sumOfLeftLeaves(Node* root)
{
if (root == NULL)
return 0;
queue<pair<Node*, bool > > q;
q.push({ root, 0 });
int sum = 0;
while (!q.empty()) {
Node* temp = q.front().first;
bool is_left_child =
q.front().second;
q.pop();
if (!temp->left && !temp->right &&
is_left_child)
sum = sum + temp->key;
if (temp->left) {
q.push({ temp->left, 1 });
}
if (temp->right) {
q.push({ temp->right, 0 });
}
}
return sum;
}
int main()
{
Node* root = new Node(20);
root->left = new Node(9);
root->right = new Node(49);
root->right->left = new Node(23);
root->right->right = new Node(52);
root->right->right->left = new Node(50);
root->left->left = new Node(5);
root->left->right = new Node(12);
root->left->right->right = new Node(12);
cout << "Sum of left leaves is "
<< sumOfLeftLeaves(root) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int key;
Node left, right;
Node( int key_)
{
key = key_;
left = null ;
right = null ;
}
};
static class pair
{
Node first;
boolean second;
public pair(Node first, boolean second)
{
this .first = first;
this .second = second;
}
}
static int sumOfLeftLeaves(Node root)
{
if (root == null )
return 0 ;
Queue<pair > q = new LinkedList<>();
q.add( new pair( root, false ));
int sum = 0 ;
while (!q.isEmpty())
{
Node temp = q.peek().first;
boolean is_left_child =
q.peek().second;
q.remove();
if (is_left_child)
sum = sum + temp.key;
if (temp.left != null && temp.right != null && is_left_child)
sum = sum-temp.key;
if (temp.left != null )
{
q.add( new pair( temp.left, true ));
}
if (temp.right != null )
{
q.add( new pair( temp.right, false ));
}
}
return sum;
}
public static void main(String[] args)
{
Node root = new Node( 20 );
root.left = new Node( 9 );
root.right = new Node( 49 );
root.right.left = new Node( 23 );
root.right.right = new Node( 52 );
root.right.right.left = new Node( 50 );
root.left.left = new Node( 5 );
root.left.right = new Node( 12 );
root.left.right.right = new Node( 12 );
System.out.print( "Sum of left leaves is "
+ sumOfLeftLeaves(root) + "\n" );
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , x):
self .key = x
self .left = None
self .right = None
def sumOfLeftLeaves(root):
if (root = = None ):
return 0
q = deque()
q.append([root, 0 ])
sum = 0
while ( len (q) > 0 ):
temp = q[ 0 ][ 0 ]
is_left_child = q[ 0 ][ 1 ]
q.popleft()
if ( not temp.left and
not temp.right and
is_left_child):
sum = sum + temp.key
if (temp.left):
q.append([temp.left, 1 ])
if (temp.right):
q.append([temp.right, 0 ])
return sum
if __name__ = = '__main__' :
root = Node( 20 )
root.left = Node( 9 )
root.right = Node( 49 )
root.right.left = Node( 23 )
root.right.right = Node( 52 )
root.right.right.left = Node( 50 )
root.left.left = Node( 5 )
root.left.right = Node( 12 )
root.left.right.right = Node( 12 )
print ( "Sum of left leaves is" ,
sumOfLeftLeaves(root))
|
Output
Sum of left leaves is 78
Time Complexity: O(N)
Auxiliary Space: O(N)
This article is contributed by Manish. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.