The Wayback Machine - https://web.archive.org/web/20240923143338/https://www.geeksforgeeks.org/find-sum-left-leaves-given-binary-tree/
Open In App

Find sum of all left leaves in a given Binary Tree

Last Updated : 10 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
45.47%
32.7K

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.

Recommended Practice

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++




// A C++ program to find sum of all left leaves
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree Node has key, pointer to left and right
   children */
struct Node
{
    int key;
    struct Node* left, *right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointer. */
Node *newNode(int k)
{
    Node *node = new Node;
    node->key = k;
    node->right = node->left = NULL;
    return node;
}
 
// A utility function to check if a given node is leaf or not
bool isLeaf(Node *node)
{
   if (node == NULL)
       return false;
   if (node->left == NULL && node->right == NULL)
       return true;
   return false;
}
 
// This function returns sum of all left leaves in a given
// binary tree
int leftLeavesSum(Node *root)
{
    // Initialize result
    int res = 0;
 
    // Update result if root is not NULL
    if (root != NULL)
    {
       // If left of root is NULL, then add key of
       // left child
       if (isLeaf(root->left))
            res += root->left->key;
       else // Else recur for left child of root
            res += leftLeavesSum(root->left);
 
       // Recur for right child of root and update res
       res += leftLeavesSum(root->right);
    }
 
    // return result
    return res;
}
 
/* Driver program to test above functions*/
int main()
{
    // Let us a construct the Binary Tree
    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;
}
 
// This code is contributed by Aditya kumar (adityakumar129)


C




// A C++ program to find sum of all left leaves
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
 
/* A binary tree Node has key, pointer to left and right
   children */
struct Node
{
  int key;
  struct Node* left, *right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointer. */
struct Node *newNode(int k)
{
  struct Node *node = (struct Node *)malloc(sizeof(struct Node));
  node->key = k;
  node->right = node->left = NULL;
  return node;
}
 
// A utility function to check if a given node is leaf or not
bool isLeaf(struct Node *node)
{
  if (node == NULL)
    return false;
  if (node->left == NULL && node->right == NULL)
    return true;
  return false;
}
 
// This function returns sum of all left leaves in a given
// binary tree
int leftLeavesSum(struct Node *root)
{
  // Initialize result
  int res = 0;
 
  // Update result if root is not NULL
  if (root != NULL)
  {
    // If left of root is NULL, then add key of
    // left child
    if (isLeaf(root->left))
      res += root->left->key;
    else // Else recur for left child of root
      res += leftLeavesSum(root->left);
 
    // Recur for right child of root and update res
    res += leftLeavesSum(root->right);
  }
 
  // return result
  return res;
}
 
/* Driver program to test above functions*/
int main()
{
  // Let us a construct the Binary Tree
  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;
}
 
// This code is contributed by Aditya kumar (adityakumar129)


Java




// Java program to find sum of all left leaves
class Node
{
    int data;
    Node left, right;
  
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
  
class BinaryTree
{
    Node root;
  
    // A utility function to check if a given node is leaf or not
    boolean isLeaf(Node node)
    {
        if (node == null)
            return false;
        if (node.left == null && node.right == null)
            return true;
        return false;
    }
  
     // This function returns sum of all left leaves in a given
     // binary tree
    int leftLeavesSum(Node node)
    {
        // Initialize result
        int res = 0;
  
        // Update result if root is not NULL
        if (node != null)
        {
            // If left of root is NULL, then add key of
            // left child
            if (isLeaf(node.left))
                res += node.left.data;
            else // Else recur for left child of root
                res += leftLeavesSum(node.left);
  
            // Recur for right child of root and update res
            res += leftLeavesSum(node.right);
        }
  
        // return result
        return res;
    }
  
    // Driver program
    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));
    }
}
  
// This code is contributed by Mayank Jaiswal


Python3




# Python program to find sum of all left leaves
 
# A Binary tree node
class Node:
    # Constructor to create a new Node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
# A utility function to check if a given node is leaf or not
def isLeaf(node):
    if node is None:
        return False
    if node.left is None and node.right is None:
        return True
    return False
 
# This function return sum of all left leaves in a
# given binary tree
def leftLeavesSum(root):
 
    # Initialize result
    res = 0
     
    # Update result if root is not None
    if root is not None:
 
        # If left of root is None, then add key of
        # left child
        if isLeaf(root.left):
            res += root.left.key
        else:
            # Else recur for left child of root
            res += leftLeavesSum(root.left)
 
        # Recur for right child of root and update res
        res += leftLeavesSum(root.right)
    return res
 
# Driver program to test above function
 
# Let us construct the Binary Tree shown in the above function
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))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




using System;
 
// C# program to find sum of all left leaves
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;
 
    // A utility function to check if a given node is leaf or not
    public virtual bool isLeaf(Node node)
    {
        if (node == null)
        {
            return false;
        }
        if (node.left == null && node.right == null)
        {
            return true;
        }
        return false;
    }
 
     // This function returns sum of all left leaves in a given
     // binary tree
    public virtual int leftLeavesSum(Node node)
    {
        // Initialize result
        int res = 0;
 
        // Update result if root is not NULL
        if (node != null)
        {
            // If left of root is NULL, then add key of
            // left child
            if (isLeaf(node.left))
            {
                res += node.left.data;
            }
            else // Else recur for left child of root
            {
                res += leftLeavesSum(node.left);
            }
 
            // Recur for right child of root and update res
            res += leftLeavesSum(node.right);
        }
 
        // return result
        return res;
    }
 
    // Driver program
    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));
    }
}
 
  //  This code is contributed by Shrikant13


Javascript




<script>
// Javascript program to find sum of all left leaves
     
    class Node
    {
        constructor(k)
        {
            this.data = k;
            this.left = null;
            this.right = null;
        }
         
    }
     
    // A utility function to check if a given node is leaf or not
    function isLeaf(node)
    {
        if (node == null)
            return false;
        if (node.left == null && node.right == null)
            return true;
        return false;
    }
     
    // This function returns sum of all left leaves in a given
     // binary tree
    function leftLeavesSum(node)
    {
     
        // Initialize result
        let res = 0;
   
        // Update result if root is not NULL
        if (node != null)
        {
         
            // If left of root is NULL, then add key of
            // left child
            if (isLeaf(node.left))
                res += node.left.data;
            else // Else recur for left child of root
                res += leftLeavesSum(node.left);
   
            // Recur for right child of root and update res
            res += leftLeavesSum(node.right);
        }
   
        // return result
        return res;
    }
     
    // Driver program
    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));
         
    // This code is contributed by unknown2108
</script>


Output

Sum 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++




// A C++ program to find sum of all left leaves
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree Node has key, pointer to left and right
   children */
struct Node
{
    int key;
    struct Node* left, *right;
};
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointer. */
Node *newNode(char k)
{
    Node *node = new Node;
    node->key = k;
    node->right = node->left = NULL;
    return node;
}
 
/* Pass in a sum variable as an accumulator */
void leftLeavesSumRec(Node *root, bool isleft, int *sum)
{
    if (!root) return;
 
    // Check whether this node is a leaf node and is left.
    if (!root->left && !root->right && isleft)
        *sum += root->key;
 
    // Pass 1 for left and 0 for right
    leftLeavesSumRec(root->left,  1, sum);
    leftLeavesSumRec(root->right, 0, sum);
}
 
// A wrapper over above recursive function
int leftLeavesSum(Node *root)
{
    int sum = 0; //Initialize result
 
    // use the above recursive function to evaluate sum
    leftLeavesSumRec(root, 0, ∑);
 
    return sum;
}
 
/* Driver program to test above functions*/
int main()
{
    // Let us construct the Binary Tree shown in the
    // above figure
    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




// Java program to find sum of all left leaves
class Node
{
    int data;
    Node left, right;
  
    Node(int item) {
        data = item;
        left = right = null;
    }
}
  
// Passing sum as accumulator and implementing pass by reference
// of sum variable
class Sum
{
    int sum = 0;
}
  
class BinaryTree
{
    Node root;
  
    /* Pass in a sum variable as an accumulator */
    void leftLeavesSumRec(Node node, boolean isleft, Sum summ)
    {
        if (node == null)
            return;
  
        // Check whether this node is a leaf node and is left.
        if (node.left == null && node.right == null && isleft)
            summ.sum = summ.sum + node.data;
  
        // Pass true for left and false for right
        leftLeavesSumRec(node.left, true, summ);
        leftLeavesSumRec(node.right, false, summ);
    }
  
    // A wrapper over above recursive function
    int leftLeavesSum(Node node)
    {
        Sum suum = new Sum();
         
        // use the above recursive function to evaluate sum
        leftLeavesSumRec(node, false, suum);
  
        return suum.sum;
    }
  
    // Driver program
    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));
    }
}
  
// This code is contributed by Mayank Jaiswal


Python3




# Python program to find sum of all left leaves
 
# A binary tree node
class Node:
 
    # A constructor to create a new Node
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
 
def leftLeavesSumRec(root, isLeft, summ):
    if root is None:
        return
     
    # Check whether this node is a leaf node and is left
    if root.left is None and root.right is None and isLeft == True:
        summ[0] += root.key
 
    # Pass 1 for left and 0 for right
    leftLeavesSumRec(root.left, 1, summ)
    leftLeavesSumRec(root.right, 0, summ)
     
 
# A wrapper over above recursive function
def leftLeavesSum(root):
    summ = [0] # initialize result
     
    # Use the above recursive function to evaluate sum
    leftLeavesSumRec(root, 0, summ)
     
    return summ[0]
 
# Driver program to test above function
 
# Let us construct the Binary Tree shown in the
# above figure
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))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




using System;
 
// C# program to find sum of all left leaves
public class Node
{
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
// Passing sum as accumulator and implementing pass by reference 
// of sum variable 
public class Sum
{
    public int sum = 0;
}
 
public class BinaryTree
{
    public Node root;
 
    /* Pass in a sum variable as an accumulator */
    public virtual void leftLeavesSumRec(Node node, bool isleft, Sum summ)
    {
        if (node == null)
        {
            return;
        }
 
        // Check whether this node is a leaf node and is left.
        if (node.left == null && node.right == null && isleft)
        {
            summ.sum = summ.sum + node.data;
        }
 
        // Pass true for left and false for right
        leftLeavesSumRec(node.left, true, summ);
        leftLeavesSumRec(node.right, false, summ);
    }
 
    // A wrapper over above recursive function
    public virtual int leftLeavesSum(Node node)
    {
        Sum suum = new Sum();
 
        // use the above recursive function to evaluate sum
        leftLeavesSumRec(node, false, suum);
 
        return suum.sum;
    }
 
    // Driver program
    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));
    }
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
// javascript program to find sum of all left leaves
class Node {
    constructor(item) {
        this.data = item;
        this.left = this.right = null;
    }
}
 
// Passing sum as accumulator and implementing pass by reference
// of sum variable
class Sum {
constructor(){
    this.sum = 0;
    }
}
 
 
    var root;
 
    /* Pass in a sum variable as an accumulator */
    function leftLeavesSumRec( node,  isleft,  summ) {
        if (node == null)
            return;
 
        // Check whether this node is a leaf node and is left.
        if (node.left == null && node.right == null && isleft)
            summ.sum = summ.sum + node.data;
 
        // Pass true for left and false for right
        leftLeavesSumRec(node.left, true, summ);
        leftLeavesSumRec(node.right, false, summ);
    }
 
    // A wrapper over above recursive function
    function leftLeavesSum( node) {
         suum = new Sum();
 
        // use the above recursive function to evaluate sum
        leftLeavesSumRec(node, false, suum);
 
        return suum.sum;
    }
 
    // Driver program
     
         
        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));
 
// This code contributed by gauravrajput1
</script>


Output

Sum 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)
{
    // base case
    if (!node)
        return 0;
    // check whether this node is a leaf node and is left.
    if (!node->left && !node->right && isleft)
        return node->key;
 
    // recursive case
    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;
}
 
// This code is contributed by Modem Upendra


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)
{
    // base case:
    if (node == NULL)
        return 0;
    // check whether this node is a leaf node and is left.
    if (node->left == NULL && node->right == NULL && isLeft)
        return node->data;
 
    // recursive case
    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)
  {
    // base case:
    if (node == null)
      return 0;
    // check whether this node is a leaf node and is left.
    if (node.left == null && node.right == null && isLeft)
      return node.data;
 
    // recursive case
    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));
 
  }
}
 
// This code is contributed by umadevi9616


Python3




# Python code for the above approach
class Node:
    def __init__(self, k):
        self.data = k
        self.left = None
        self.right = None
         
def sumAllLeftLeaves(node, isleft):
    # base case
    if node is None:
        return 0
         
    # check whether this node is a leaf node and is left.
    if node.left is None and node.right is None and isleft:
        return node.data
 
    # recursive case
    return sumAllLeftLeaves(node.left, True) + sumAllLeftLeaves(node.right, False)
 
# Driver program
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)))
 
# This code is contributed by Potta Lokesh


C#




// C# implementation
 
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)
    {
        // base case:
        if (node == null)
            return 0;
        // check whether this node is a leaf node and is
        // left.
        if (node.left == null && node.right == null
            && isLeft)
            return node.data;
 
        // recursive case
        return sumAllLeaftLeaves(node.left, true)
            + sumAllLeaftLeaves(node.right, false);
    }
 
    static public void Main()
    {
 
        // Code
        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));
    }
}
 
// This code is contributed by lokesh


Javascript




class Node
    {
        constructor(k)
        {
            this.data = k;
            this.left = null;
            this.right = null;
        }
         
    }
function sumAllLeftLeaves(node, isleft)
{
    // base case
    if (node == null)
        return 0;
         
    // check whether this node is a leaf node and is left.
    if (node.left==null && node.right==null && isleft==true)
        return node.data;
 
    // recursive case
    return sumAllLeftLeaves(node.left, true)
           + sumAllLeftLeaves(node.right, false);
}
 
 
       // Driver program
    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));
 
    // This code is contributed by garg28harsh.


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++




// C++ program to find sum of all left leaves
#include<bits/stdc++.h>
using namespace std;
 
// A binary tree node
class Node
{
    public:
    int key;
    Node* left, *right;
     
    // A constructor to create a new Node
    Node(int key_)
    {
        key = key_;
        left = NULL;
        right = NULL;
    }
};
 
// Return the sum of left leaf nodes
int sumOfLeftLeaves(Node* root)
{
    if(root == NULL)
        return 0;
     
    // Using a stack_ for Depth-First
    // Traversal of the tree
    stack<Node*> stack_;
    stack_.push(root);
     
    // sum holds the sum of all the left leaves
    int sum = 0;
 
    while(stack_.size() > 0)
    {
        Node* currentNode = stack_.top();
        stack_.pop();
 
        if (currentNode->left != NULL)
        {
            stack_.push(currentNode->left);
             
            // Check if currentNode's left
            // child is a leaf node
            if(currentNode->left->left == NULL &&
               currentNode->left->right == NULL)
            {
                // if currentNode is a leaf,
                // add its data to the sum
                sum = sum + currentNode->left->key ;
            }
        }
        if (currentNode->right != NULL)
            stack_.push(currentNode->right);
    }
         
    return sum;
}
 
// Driver Code
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;
}
 
// This code is contributed by Arnab Kundu


Java




// Java program to find sum of all left leaves
import java.util.*;
class GFG
{
 
// A binary tree node
static class Node
{
    int key;
    Node left, right;
     
    // A constructor to create a new Node
    Node(int key_)
    {
        this.key = key_;
        this.left = null;
        this.right = null;
    }
};
 
// Return the sum of left leaf nodes
static int sumOfLeftLeaves(Node root)
{
    if(root == null)
    return 0;
     
    // Using a stack_ for Depth-First
    // Traversal of the tree
    Stack<Node> stack_ = new Stack<>();
    stack_.push(root);
     
    // sum holds the sum of all the left leaves
    int sum = 0;
 
    while(stack_.size() > 0)
    {
        Node currentNode = stack_.peek();
        stack_.pop();
 
        if (currentNode.left != null)
        {
            stack_.add(currentNode.left);
             
            // Check if currentNode's left
            // child is a leaf node
            if(currentNode.left.left == null &&
               currentNode.left.right == null)
            {
                // if currentNode is a leaf,
                // add its data to the sum
                sum = sum + currentNode.left.key ;
            }
        }
        if (currentNode.right != null)
            stack_.add(currentNode.right);
    }      
    return sum;
}
 
// Driver Code
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");
}
}
 
// This code is contributed by aashish1995


Python3




# Python3 program to find sum of all left leaves
 
# A binary tree node
class Node:
 
    # A constructor to create a new Node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
 
# Return the sum of left leaf nodes
def sumOfLeftLeaves(root):
    if(root is None):
        return
     
    # Using a stack for Depth-First Traversal of the tree
    stack = []  
    stack.append(root)
     
    # sum holds the sum of all the left leaves
    sum = 0
 
    while len(stack) > 0:
        currentNode = stack.pop()
        if currentNode.left is not None:
            stack.append(currentNode.left)
             
            # Check if currentNode's left child is a leaf node
            if currentNode.left.left is None and currentNode.left.right is None:
 
                # if currentNode is a leaf, add its data to the sum 
                sum = sum + currentNode.left.data
 
        if currentNode.right is not None:
            stack.append(currentNode.right)
    return sum
 
# Driver Code
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#




// C# program to find sum of all left leaves
using System;
using System.Collections.Generic;
class GFG
{
 
  // A binary tree node
  public
    class Node
    {
      public
        int key;
      public
        Node left, right;
 
      // A constructor to create a new Node
      public
        Node(int key_)
      {
        this.key = key_;
        this.left = null;
        this.right = null;
      }
    };
 
  // Return the sum of left leaf nodes
  static int sumOfLeftLeaves(Node root)
  {
    if(root == null)
      return 0;
 
    // Using a stack_ for Depth-First
    // Traversal of the tree
    Stack<Node> stack_ = new Stack<Node>();
    stack_.Push(root);
 
    // sum holds the sum of all the left leaves
    int sum = 0;
    while(stack_.Count > 0)
    {
      Node currentNode = stack_.Peek();
      stack_.Pop();
      if (currentNode.left != null)
      {
        stack_.Push(currentNode.left);
 
        // Check if currentNode's left
        // child is a leaf node
        if(currentNode.left.left == null &&
           currentNode.left.right == null)
        {
 
          // if currentNode is a leaf,
          // add its data to the sum
          sum = sum + currentNode.left.key ;
        }
      }
      if (currentNode.right != null)
        stack_.Push(currentNode.right);
    }      
    return sum;
  }
 
  // Driver Code
  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");
  }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
  
 
// JavaScript program to find sum of all left leaves
// A binary tree node
class Node
{
 
  // A constructor to create a new Node
  constructor(key_)
  {
    this.key = key_;
    this.left = null;
    this.right = null;
  }
};
// Return the sum of left leaf nodes
function sumOfLeftLeaves(root)
{
  if(root == null)
    return 0;
  // Using a stack_ for Depth-First
  // Traversal of the tree
  var stack_ = [];
  stack_.push(root);
  // sum holds the sum of all the left leaves
  var sum = 0;
  while(stack_.length > 0)
  {
    var currentNode = stack_[stack_.length-1];
    stack_.pop();
    if (currentNode.left != null)
    {
      stack_.push(currentNode.left);
      // Check if currentNode's left
      // child is a leaf node
      if(currentNode.left.left == null &&
         currentNode.left.right == null)
      {
        // if currentNode is a leaf,
        // add its data to the sum
        sum = sum + currentNode.left.key ;
      }
    }
    if (currentNode.right != null)
      stack_.push(currentNode.right);
  }      
  return sum;
}
 
// Driver Code
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>


Output

Sum 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++




// C++ program to find sum of all left leaves
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node
class Node {
public:
    int key;
    Node *left, *right;
 
    // constructor to create a new Node
    Node(int key_)
    {
        key = key_;
        left = NULL;
        right = NULL;
    }
};
 
// Return the sum of left leaf nodes
int sumOfLeftLeaves(Node* root)
{
    if (root == NULL)
        return 0;
    // A queue of pairs to do bfs traversal
    // and keep track if the node is a left
    // or right child if boolean value
    // is true then it is a left child.
    queue<pair<Node*, bool> > q;
    q.push({ root, 0 });
    int sum = 0;
    // do bfs traversal
    while (!q.empty()) {
        Node* temp = q.front().first;
        bool is_left_child =
                   q.front().second;
        q.pop();
        // if temp is a leaf node and
        // left child of its parent
        if (!temp->left && !temp->right &&
                            is_left_child)
            sum = sum + temp->key;
        // if it is not leaf then
        // push its children nodes
        // into queue
        if (temp->left) {
            // boolean value is true
            // here because it is left
            // child of its parent
            q.push({ temp->left, 1 });
        }
        if (temp->right) {
            // boolean value is false
            // here because it is
            // right child of its parent
            q.push({ temp->right, 0 });
        }
    }
    return sum;
}
 
// Driver Code
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




// Java program to find sum of all left leaves
import java.util.*;
class GFG
{
 
// A binary tree node
static class Node
{
    int key;
    Node left, right;
 
    // constructor to create a new Node
    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;
    }   
}
   
// Return the sum of left leaf nodes
static int sumOfLeftLeaves(Node root)
{
    if (root == null)
    return 0;
   
    // A queue of pairs to do bfs traversal
    // and keep track if the node is a left
    // or right child if boolean value
    // is true then it is a left child.
    Queue<pair > q = new LinkedList<>();
    q.add(new pair( root, false ));
    int sum = 0;
   
    // do bfs traversal
    while (!q.isEmpty())
    {
        Node temp = q.peek().first;
        boolean is_left_child =
                   q.peek().second;
        q.remove();
       
        // if temp is a leaf node and
        // left child of its parent
        if (is_left_child)
            sum = sum + temp.key;
        if(temp.left != null && temp.right != null && is_left_child)
            sum = sum-temp.key;
       
        // if it is not leaf then
        // push its children nodes
        // into queue
        if (temp.left != null)
        {
           
            // boolean value is true
            // here because it is left
            // child of its parent
            q.add(new pair( temp.left, true));
        }
        if (temp.right != null)
        {
           
            // boolean value is false
            // here because it is
            // right child of its parent
            q.add(new pair( temp.right, false));
        }
    }
    return sum;
}
 
// Driver Code
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");
}
}
 
// This code is contributed by gauravrajput1.


Python3




# Python3 program to find sum of
# all left leaves
from collections import deque
 
# A binary tree node
class Node:
     
    def __init__(self, x):
         
        self.key = x
        self.left = None
        self.right = None
 
# Return the sum of left leaf nodes
def sumOfLeftLeaves(root):
     
    if (root == None):
        return 0
         
    # A queue of pairs to do bfs traversal
    # and keep track if the node is a left
    # or right child if boolean value
    # is true then it is a left child.
    q = deque()
    q.append([root, 0])
    sum = 0
     
    # Do bfs traversal
    while (len(q) > 0):
        temp = q[0][0]
        is_left_child = q[0][1]
        q.popleft()
         
        # If temp is a leaf node and
        # left child of its parent
        if (not temp.left and
            not temp.right and
            is_left_child):
            sum = sum + temp.key
             
        # If it is not leaf then
        # push its children nodes
        # into queue
        if (temp.left):
             
            # Boolean value is true
            # here because it is left
            # child of its parent
            q.append([temp.left, 1])
             
        if (temp.right):
             
            # Boolean value is false
            # here because it is
            # right child of its parent
            q.append([temp.right, 0])
 
    return sum
 
# Driver Code
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))
 
# This code is contributed by mohit kumar 29


C#




// C# program to find sum of all left leaves
using System;
using System.Collections.Generic;
public class GFG
{
 
  // A binary tree node
  public
 
    class Node
    {
      public int key;
      public
 
        Node left,
      right;
 
      // constructor to create a new Node
      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;
      }
    }
 
  // Return the sum of left leaf nodes
  static int sumOfLeftLeaves(Node root)
  {
    if (root == null)
      return 0;
 
    // A queue of pairs to do bfs traversal
    // and keep track if the node is a left
    // or right child if bool value
    // is true then it is a left child.
    Queue<pair> q = new Queue<pair>();
    q.Enqueue(new pair(root, false));
    int sum = 0;
 
    // do bfs traversal
    while (q.Count != 0)
    {
      Node temp = q.Peek().first;
      bool is_left_child = q.Peek().second;
      q.Dequeue();
 
      // if temp is a leaf node and
      // left child of its parent
      if (is_left_child)
        sum = sum + temp.key;
      if (temp.left != null && temp.right != null
          && is_left_child)
        sum = sum - temp.key;
 
      // if it is not leaf then
      // push its children nodes
      // into queue
      if (temp.left != null)
      {
 
        // bool value is true
        // here because it is left
        // child of its parent
        q.Enqueue(new pair(temp.left, true));
      }
      if (temp.right != null)
      {
 
        // bool value is false
        // here because it is
        // right child of its parent
        q.Enqueue(new pair(temp.right, false));
      }
    }
    return sum;
  }
 
  // Driver Code
  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");
  }
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
    // JavaScript program to find sum of all left leaves
     
    class Node
    {
        constructor(key_) {
           this.left = null;
           this.right = null;
           this.key = key_;
        }
    }
   
    // Return the sum of left leaf nodes
    function sumOfLeftLeaves(root)
    {
        if (root == null)
            return 0;
 
        // A queue of pairs to do bfs traversal
        // and keep track if the node is a left
        // or right child if boolean value
        // is true then it is a left child.
        let q = [];
        q.push([root, false ]);
        let sum = 0;
 
        // do bfs traversal
        while (q.length > 0)
        {
            let temp = q[0][0];
            let is_left_child =
                       q[0][1];
            q.shift();
 
            // if temp is a leaf node and
            // left child of its parent
            if (is_left_child)
                sum = sum + temp.key;
            if(temp.left != null &&
            temp.right != null && is_left_child)
                sum = sum-temp.key;
 
            // if it is not leaf then
            // push its children nodes
            // into queue
            if (temp.left != null)
            {
 
                // boolean value is true
                // here because it is left
                // child of its parent
                q.push([temp.left, true]);
            }
            if (temp.right != null)
            {
 
                // boolean value is false
                // here because it is
                // right child of its parent
                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>


Output

Sum of left leaves is 78

Time Complexity: O(N)
Auxiliary Space: O(N)



Similar Reads

Tree with N nodes and K leaves such that distance between farthest leaves is minimized
Given N and K, print a tree such that the tree has no more than K leaf nodes and every other node has at least two nodes connected to it. The task is to build a tree of N nodes exactly in such a way that the distance between the farthest leaf nodes is minimized. Print the minimized distance also. Note: There can be multiple trees. Examples: Input:
6 min read
Find sum of all right leaves in a given Binary Tree
Given a Binary Tree, find sum of all right leaves in it. Similar article: Find sum of all left leaves in a given Binary Tree Example : Input : 1 / \ 2 3 / \ \ 4 5 8 \ / \ 2 6 7 Output : sum = 2 + 5 + 7 = 14Recommended PracticePaths from root with a specified sumTry It! Method 1: Recursive Method The idea is to traverse the tree starting from the ro
15+ min read
Find the maximum path sum between two leaves of a binary tree
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. The maximum sum path may or may not go through the root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 - 1 + 10). Expected time complexity is O(n). If one side of the root is empty, then the
13 min read
Print all nodes in a binary tree having K leaves
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommended PracticePrint Nodes having K leavesTry It! Here
7 min read
Minimum sum path between two leaves of a binary tree
Given a binary tree in which each node element contains a number. The task is to find the minimum possible sum from one leaf node to another.If one side of root is empty, then function should return minus infinite.Examples: Input : 4 / \ 5 -6 / \ / \ 2 -3 1 8 Output : 1 The minimum sum path between two leaf nodes is: -3 -&gt; 5 -&gt; 4 -&gt; -6 -
10 min read
Height of binary tree considering even level leaves only
Find the height of the binary tree given that only the nodes on the even levels are considered valid leaf nodes. The height of a binary tree is the number of edges between the tree's root and its furthest leaf. But what if we bring a twist and change the definition of a leaf node? Let us define a valid leaf node as the node that has no children and
8 min read
Lowest Common Ancestor of the deepest leaves of a Binary Tree
Given a Binary Tree consisting of N nodes having distinct values from the range [1, N], the task is to find the lowest common ancestor of the deepest leaves of the binary tree. Examples: Input: Output: 1Explanation: The deepest leaf nodes of the tree are {8, 9, 10}. Lowest common ancestor of these nodes is 1. Input: Output: 6 Approach: The given pr
10 min read
Extract Leaves of a Binary Tree in a Doubly Linked List
Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer, and right means next pointer. Let the following be input binary tre
11 min read
All Leaves of a Bnary Tree - Print in Order
Given a binary tree, we need to print all leaf nodes of the given binary tree from left to right. That is, the nodes should be printed in the order they appear from left to right in the given tree.  For Example,  Input : Root of the below tree Output : 4 6 7 9 10 Corner Cases : For a tree with single node, the output should be the single node. And
11 min read
Minimum number of leaves required to be removed from a Tree to satisfy the given condition
Given a Tree consisting of N vertices, rooted at vertex 1 and an array val[] representing the values assigned to each vertex, and an array cost[] representing the cost of each edge in the Tree, the task is to find the minimum number of leaves to be removed from the given tree such that: For any vertex V, the sum of cost of edges to a vertex U in it
8 min read
Find first non matching leaves in two binary trees
Given two binary trees, find the first leaves of two trees that do not match. If there are no non-matching leaves, print nothing. Examples: Input : First Tree 5 / \ 2 7 / \ 10 11 Second Tree 6 / \ 10 15 Output : 11 15 If we consider leaves of two trees in order, we can see that 11 and 15 are the first leaves that do not match. Method 1 (Simple) : D
14 min read
Change a Binary Tree so that every node stores sum of all nodes in left subtree
Given a Binary Tree, change the value in each node to sum of all the values in the nodes in the left subtree including its own. Examples: Input : 1 / \ 2 3 Output : 3 / \ 2 3 Input 1 / \ 2 3 / \ \ 4 5 6 Output: 12 / \ 6 3 / \ \ 4 5 6 We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse the given tre
8 min read
Generate Array whose sum of all K-size subarrays divided by N leaves remainder X
Given three integer N, K and X, the task is to create an array of length N such that sum of all its K-length subarrays modulo N is X.Examples: Input: N = 6, K = 3, X = 3 Output: 9 6 6 9 6 6 Explanation: All subarrays of length 3 and their respective sum%N values are as follows: [9, 6, 6] Sum = 21 % 6 = 3 [6, 6, 9] sum = 21 % 6 = 3 [6, 9, 6] sum = 2
4 min read
Sum of nodes in the left view of the given binary tree
Given a binary tree, the task is to find the sum of the nodes which are visible in the left view. The left view of a binary tree is the set of nodes visible when the tree is viewed from the left.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 7 1 + 2 + 4 = 7 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 18 Approach: The problem can be solved using simple rec
9 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Minimum count of Full Binary Trees such that the count of leaves is N
Given an integer N and an infinite number of Full Binary Trees of different depths, the task is to choose minimum number of trees such that the sum of the count of leaf nodes in each of the tree is N.Example: Input: N = 7 Output: 3 Trees with depths 2, 1 and 0 can be picked with the number of leaf nodes as 4, 2 and 1 respectively. (4 + 2 + 1) = 7In
3 min read
Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
Given a Binary Tree, the task is to print the leaf nodes from left to right. The nodes must be printed in the order they appear from left to right.Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output :4 5 6 7 Input : 4 / \ 5 9 / \ / \ 8 3 7 2 / / \ 12 6 1 Output :12 3 7 6 1 We have already discussed the Recursive approach. Here we will solve the prob
8 min read
Print all leaf nodes of a binary tree from right to left
Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 6 5 4 Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 4 Recursive Approach: Traverse the tree in Preorder fashion, by first processing the root, then right subtree and then left subtree
14 min read
Left rotate digits of node values of all levels of a Binary Tree in increasing order
Given a Binary Tree, the task is to modify the Tree by left rotating every node any number of times such that every level consists of node values in increasing order from left to right. If it is not possible to arrange node values of any level in increasing order, then print "-1". Examples: Input: 341 / \ 241 123 / \ \ 324 235 161Output: 341 / \ 12
14 min read
Sum of nodes in a binary tree having only the left child nodes
Given a binary tree, the task is to find the sum of binary tree nodes having only the left child nodes. Example: Input: 8 / \ 3 7 / \ / 5 6 0 / / 1 2Output: 18 Explanation: Nodes with values 5, 6, and 7 are the ones that have only the left child nodes Input: 2 / \ 3 1 / / 5 6Output: 4 Approach: The given problem can be solved by traversing the bina
6 min read
Check if N leaves only distinct remainders on division by all values up to K
Given a two integers N and K, the task is to check if N leaves only distinct remainders when divided by all integers in the range [1, K]. If so, print Yes. Otherwise, print No.Examples: Input: N = 5, K = 3 Output: Yes Explanation: (5 % 1) == 0 (5 % 2) == 1 (5 % 3) == 2 Since all the remainders {0, 1, 2} are distinct.Input: N = 5, K = 4 Output: No E
4 min read
Check if all leaves are at same level
Given a Binary Tree, check if all leaves are at same level or not. 12 / \ 5 7 / \ 3 1 Leaves are at same level 12 / \ 5 7 / 3 Leaves are Not at same level 12 / 5 / \ 3 9 / / 1 2 Leaves are at same level Recommended PracticeLeaf at same levelTry It! The idea is to first find the level of the leftmost leaf and store it in a variable leafLevel. Then c
15+ min read
Count of nodes with average of left subtree at least K in a given Binary Tree
Given a binary tree and a number K, the task is to count the number of nodes having the average of the values in their left subtree greater than or equal to K. Examples: Input : K=5Tree: 2 / \ 5 4 / \ / \ 5 6 6 2 \ / 5 4Output: 3Explanation: 2 -------- level 0 / \ 5 4 -------- level 1 / \ / \ 5 6 6 2 -------- level 2 \ / 5 4 -------- level 3 Left l
15+ min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Find product of sums of data of leaves at same levels | Set 2
Given a Binary Tree, return following value for it. For every level, compute sum of all leaves if there are leaves at this level. Otherwise ignore it.Return multiplication of all sums. Examples: Input: Root of below tree 2 / \ 7 5 \ 9 Output: 63 First levels doesn't have leaves. Second level has one leaf 7 and third level also has one leaf 9. There
9 min read
Find multiplication of sums of data of leaves at same levels
Given a Binary Tree, return following value for it. 1) For every level, compute sum of all leaves if there are leaves at this level. Otherwise, ignore it. 2) Return multiplication of all sums.Examples: Input: Root of below tree 2 / \ 7 5 \ 9Output: 63First levels doesn't have leaves. Second levelhas one leaf 7 and third level also has one leaf 9. T
15+ min read
Largest number by which given 3 numbers should be divided such that they leaves same remainder
Given three numbers, our task is to find the largest number by which when given 3 numbers are divided leads to same remainder. It may be assumed that all given numbers are given in increasing order. Examples: Input : a = 62, b = 132, c = 237 Output : 35 35 leads to same remainder 27 when divides 62, 132 and 237. Input : a = 74, b = 272, c = 584 Out
9 min read
Minimize K whose XOR with given array elements leaves array unchanged
Given an array of N elements, the task is to find the minimum value of K such that Bitwise XOR of K with all array elements produces the same set of elements. If it is impossible to find any value of K then print "-1". Examples: Input: arr[] = { 1, 0, 2, 3} Output: 1 Explanation: For K = 1, 1 xor 1 = 01 xor 0 = 11 xor 2 = 31 xor 3 = 2Thus, K = 1 is
7 min read
Find sum of all nodes of the given perfect binary tree
Given a positive integer L which represents the number of levels in a perfect binary tree. Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n, where n is the number of leaf nodes. And the parent node is the sum of the two child nodes. Our task is to write a program to print the sum of all of the nodes of this pe
11 min read
Queries to find the sum of weights of all nodes with vertical width from given range in a Binary Tree
Given a Binary Tree consisting of N nodes having values in the range [0, N - 1] rooted as 0, an array wt[] of size N where wt[i] is the weight of the ith node and a 2D array Q[][] consisting of queries of the type {L, R}, the task for each query is to find the sum of weights of all nodes whose vertical width lies in the range [L, R]. Examples: Inpu
11 min read
Article Tags :
Practice Tags :