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( int 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;
}
|
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node
{
int key;
struct Node* left, *right;
};
struct Node *newNode( int k)
{
struct Node *node = ( struct Node *) malloc ( sizeof ( struct Node));
node->key = k;
node->right = node->left = NULL;
return node;
}
bool isLeaf( struct Node *node)
{
if (node == NULL)
return false ;
if (node->left == NULL && node->right == NULL)
return true ;
return false ;
}
int leftLeavesSum( struct 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);
printf ( "Sum of left leaves is %d" ,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));
}
}
|
Python3
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));
}
}
|
Javascript
<script>
class Node
{
constructor(k)
{
this .data = k;
this .left = null ;
this .right = null ;
}
}
function isLeaf(node)
{
if (node == null )
return false ;
if (node.left == null && node.right == null )
return true ;
return false ;
}
function leftLeavesSum(node)
{
let res = 0;
if (node != null )
{
if (isLeaf(node.left))
res += node.left.data;
else
res += leftLeavesSum(node.left);
res += leftLeavesSum(node.right);
}
return res;
}
root = new Node(20);
root.left = new Node(9);
root.right = new Node(49);
root.left.right = new Node(12);
root.left.left = new Node(5);
root.right.left = new Node(23);
root.right.right = new Node(52);
root.left.right.right = new Node(12);
root.right.right.left = new Node(50);
document.write( "The sum of leaves is " +leftLeavesSum(root));
</script>
|
OutputSum of left leaves is 78
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of given binary tree due to recursion call.
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));
}
}
|
Python3
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));
}
}
|
Javascript
<script>
class Node {
constructor(item) {
this .data = item;
this .left = this .right = null ;
}
}
class Sum {
constructor(){
this .sum = 0;
}
}
var root;
function leftLeavesSumRec( node, isleft, 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);
}
function leftLeavesSum( node) {
suum = new Sum();
leftLeavesSumRec(node, false , suum);
return suum.sum;
}
root = new Node(20);
root.left = new Node(9);
root.right = new Node(49);
root.left.right = new Node(12);
root.left.left = new Node(5);
root.right.left = new Node(23);
root.right.right = new Node(52);
root.left.right.right = new Node(12);
root.right.right.left = new Node(50);
document.write( "The sum of leaves is " + leftLeavesSum(root));
</script>
|
OutputSum of left leaves is 78
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of given binary tree due to recursion call.
Following is Another Method to solve the above problem. We can pass bool as parameter in the function to check if it is a left or right node. Time complexity of this method is also O(n).
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
};
Node* create( int k)
{
Node* newnode = new Node();
newnode->key = k;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
int sumAllLeftLeaves(Node* node, bool isleft)
{
if (!node)
return 0;
if (!node->left && !node->right && isleft)
return node->key;
return sumAllLeftLeaves(node->left, true )
+ sumAllLeftLeaves(node->right, false );
}
int main()
{
int sum = 0;
Node* root = create(20);
root->left = create(9);
root->right = create(49);
root->right->left = create(23);
root->right->right = create(52);
root->right->right->left = create(50);
root->left->left = create(5);
root->left->right = create(12);
root->left->right->right = create(12);
cout << "Sum of left leaves is: "
<< sumAllLeftLeaves(root, false );
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
typedef struct Node str_node;
str_node* create( int item);
int sumAllLeaftLeaves(str_node* node, bool isLeft);
int main( void )
{
int d = 0;
str_node* root = create(20);
root->left = create(9);
root->right = create(49);
root->right->left = create(23);
root->right->right = create(52);
root->right->right->left = create(50);
root->left->left = create(5);
root->left->right = create(12);
root->left->right->right = create(12);
printf ( "\nSum of left leaves is: %d " ,
sumAllLeaftLeaves(root, false ));
return 0;
}
str_node* create( int item)
{
str_node* newnode = (str_node*) malloc ( sizeof (str_node));
newnode->data = item;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
int sumAllLeaftLeaves(str_node* node, bool isLeft)
{
if (node == NULL)
return 0;
if (node->left == NULL && node->right == NULL && isLeft)
return node->data;
return sumAllLeaftLeaves(node->left, true )
+ sumAllLeaftLeaves(node->right, false );
}
|
Java
class GFG{
static class Node {
int data;
Node left;
Node right;
};
static Node str_node;
static Node create( int item)
{
Node newnode = new Node();
newnode.data = item;
newnode.left = null ;
newnode.right = null ;
return newnode;
}
static int sumAllLeaftLeaves(Node node, boolean isLeft)
{
if (node == null )
return 0 ;
if (node.left == null && node.right == null && isLeft)
return node.data;
return sumAllLeaftLeaves(node.left, true )
+ sumAllLeaftLeaves(node.right, false );
}
public static void main(String[] args)
{
int d = 0 ;
Node root = create( 20 );
root.left = create( 9 );
root.right = create( 49 );
root.right.left = create( 23 );
root.right.right = create( 52 );
root.right.right.left = create( 50 );
root.left.left = create( 5 );
root.left.right = create( 12 );
root.left.right.right = create( 12 );
System.out.printf( "\nSum of left leaves is: %d " ,
sumAllLeaftLeaves(root, false ));
}
}
|
Python3
class Node:
def __init__( self , k):
self .data = k
self .left = None
self .right = None
def sumAllLeftLeaves(node, isleft):
if node is None :
return 0
if node.left is None and node.right is None and isleft:
return node.data
return sumAllLeftLeaves(node.left, True ) + sumAllLeftLeaves(node.right, False )
root = Node( 20 )
root.left = Node( 9 )
root.right = Node( 49 )
root.left.right = Node( 12 )
root.left.left = Node( 5 )
root.right.left = Node( 23 )
root.right.right = Node( 52 )
root.left.right.right = Node( 12 )
root.right.right.left = Node( 50 )
print ( "The sum of leaves is " + str (sumAllLeftLeaves(root, False )))
|
C#
using System;
public class GFG {
public class Node {
public int data;
public Node left;
public Node right;
}
static Node str_node;
static Node create( int item)
{
Node newnode = new Node();
newnode.data = item;
newnode.left = null ;
newnode.right = null ;
return newnode;
}
static int sumAllLeaftLeaves(Node node, bool isLeft)
{
if (node == null )
return 0;
if (node.left == null && node.right == null
&& isLeft)
return node.data;
return sumAllLeaftLeaves(node.left, true )
+ sumAllLeaftLeaves(node.right, false );
}
static public void Main()
{
int d = 0;
Node root = create(20);
root.left = create(9);
root.right = create(49);
root.right.left = create(23);
root.right.right = create(52);
root.right.right.left = create(50);
root.left.left = create(5);
root.left.right = create(12);
root.left.right.right = create(12);
Console.WriteLine( "\nSum of left leaves is: "
+ sumAllLeaftLeaves(root, false ));
}
}
|
Javascript
class Node
{
constructor(k)
{
this .data = k;
this .left = null ;
this .right = null ;
}
}
function sumAllLeftLeaves(node, isleft)
{
if (node == null )
return 0;
if (node.left== null && node.right== null && isleft== true )
return node.data;
return sumAllLeftLeaves(node.left, true )
+ sumAllLeftLeaves(node.right, false );
}
root = new Node(20);
root.left = new Node(9);
root.right = new Node(49)a;
root.left.right = new Node(12);
root.left.left = new Node(5);
root.right.left = new Node(23);
root.right.right = new Node(52);
root.left.right.right = new Node(12);
root.right.right.left = new Node(50);
document.write( "The sum of leaves is " +sumAllLeftLeaves(root, false ));
|
OutputSum 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 .data = 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 = 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 {}' . 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" );
}
}
|
Javascript
<script>
class Node
{
constructor(key_)
{
this .key = key_;
this .left = null ;
this .right = null ;
}
};
function sumOfLeftLeaves(root)
{
if (root == null )
return 0;
var stack_ = [];
stack_.push(root);
var sum = 0;
while (stack_.length > 0)
{
var currentNode = stack_[stack_.length-1];
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;
}
var 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);
document.write( "Sum of left leaves is "
+ sumOfLeftLeaves(root) + "<br>" );
</script>
|
OutputSum of left leaves is 78
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of given binary tree.
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))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public
class Node
{
public int key;
public
Node left,
right;
public
Node( int key_)
{
key = key_;
left = null ;
right = null ;
}
};
public
class pair {
public
Node first;
public
bool second;
public pair(Node first, bool second)
{
this .first = first;
this .second = second;
}
}
static int sumOfLeftLeaves(Node root)
{
if (root == null )
return 0;
Queue<pair> q = new Queue<pair>();
q.Enqueue( new pair(root, false ));
int sum = 0;
while (q.Count != 0)
{
Node temp = q.Peek().first;
bool is_left_child = q.Peek().second;
q.Dequeue();
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.Enqueue( new pair(temp.left, true ));
}
if (temp.right != null )
{
q.Enqueue( 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);
Console.Write( "Sum of left leaves is "
+ sumOfLeftLeaves(root) + "\n" );
}
}
|
Javascript
<script>
class Node
{
constructor(key_) {
this .left = null ;
this .right = null ;
this .key = key_;
}
}
function sumOfLeftLeaves(root)
{
if (root == null )
return 0;
let q = [];
q.push([root, false ]);
let sum = 0;
while (q.length > 0)
{
let temp = q[0][0];
let is_left_child =
q[0][1];
q.shift();
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.push([temp.left, true ]);
}
if (temp.right != null )
{
q.push([temp.right, false ]);
}
}
return sum;
}
let 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);
document.write( "Sum of left leaves is "
+ sumOfLeftLeaves(root) + "</br>" );
</script>
|
OutputSum of left leaves is 78
Time Complexity: O(N)
Auxiliary Space: O(N)
Please Login to comment...