Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Find sum of all right leaves in a given Binary Tree

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 = 14

Method 1: Recursive Method

The idea is to traverse the tree starting from the root and check if the node is the leaf node or not. If the node is the right leaf than add data of right leaf to sum variable.

Following is the implementation for the same.  

C++




// CPP program to find total sum
// of right leaf nodes
#include <bits/stdc++.h>
using namespace std;
 
// struct node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
 
// return new node
Node* addNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// utility function to calculate sum
// of right leaf nodes
void rightLeafSum(Node* root, int& sum)
{
    if (!root)
        return;
 
    // check if the right child of root
    // is leaf node
    if (root->right)
        if (root->right->left == NULL
            && root->right->right == NULL)
            sum += root->right->data;
 
    rightLeafSum(root->left, sum);
    rightLeafSum(root->right, sum);
}
 
// driver program
int main()
{
 
    // construct binary tree
    Node* root = addNode(1);
    root->left = addNode(2);
    root->left->left = addNode(4);
    root->left->right = addNode(5);
    root->left->left->right = addNode(2);
    root->right = addNode(3);
    root->right->right = addNode(8);
    root->right->right->left = addNode(6);
    root->right->right->right = addNode(7);
 
    // variable to store sum of right
    // leaves
    int sum = 0;
    rightLeafSum(root, sum);
    cout << sum << endl;
    return 0;
}


Java




// Java program to find total
// sum of right leaf nodes
class GFG {
 
    // sum
    static int sum = 0;
 
    // node of binary tree
    static class Node {
        int data;
        Node left, right;
    };
 
    // return new node
    static Node addNode(int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
    // utility function to calculate
    // sum of right leaf nodes
    static void rightLeafSum(Node root)
    {
        if (root == null)
            return;
 
        // check if the right child
        // of root is leaf node
        if (root.right != null)
            if (root.right.left == null
                && root.right.right == null)
                sum += root.right.data;
 
        rightLeafSum(root.left);
        rightLeafSum(root.right);
    }
 
    // Driver Code
    public static void main(String args[])
    {
 
        // construct binary tree
        Node root = addNode(1);
        root.left = addNode(2);
        root.left.left = addNode(4);
        root.left.right = addNode(5);
        root.left.left.right = addNode(2);
        root.right = addNode(3);
        root.right.right = addNode(8);
        root.right.right.left = addNode(6);
        root.right.right.right = addNode(7);
 
        // variable to store sum
        // of right leaves
        sum = 0;
        rightLeafSum(root);
        System.out.println(sum);
    }
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program to find total Sum
# of right leaf nodes
 
# return new node
 
 
class addNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# utility function to calculate Sum
# of right leaf nodes
 
 
def rightLeafSum(root, Sum):
    if(not root):
        return
 
    # check if the right child of root
    # is leaf node
    if(root.right):
        if(not root.right.left and
           not root.right.right):
            Sum[0] += root.right.data
 
    rightLeafSum(root.left, Sum)
    rightLeafSum(root.right, Sum)
 
 
# Driver Code
if __name__ == '__main__':
 
    # construct binary tree
    root = addNode(1)
    root.left = addNode(2)
    root.left.left = addNode(4)
    root.left.right = addNode(5)
    root.left.left.right = addNode(2)
    root.right = addNode(3)
    root.right.right = addNode(8)
    root.right.right.left = addNode(6)
    root.right.right.right = addNode(7)
 
    # variable to store Sum of right
    # leaves
    Sum = [0]
    rightLeafSum(root, Sum)
    print(Sum[0])
 
# This code is contributed by PranchalK


C#




using System;
 
// C# program to find total
// sum of right leaf nodes
public class GFG {
 
    // sum
    public static int sum = 0;
 
    // node of binary tree
    public class Node {
        public int data;
        public Node left, right;
    }
 
    // return new node
    public static Node addNode(int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
    // utility function to calculate
    // sum of right leaf nodes
    public static void rightLeafSum(Node root)
    {
        if (root == null) {
            return;
        }
 
        // check if the right child
        // of root is leaf node
        if (root.right != null) {
            if (root.right.left == null
                && root.right.right == null) {
                sum += root.right.data;
            }
        }
 
        rightLeafSum(root.left);
        rightLeafSum(root.right);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        // construct binary tree
        Node root = addNode(1);
        root.left = addNode(2);
        root.left.left = addNode(4);
        root.left.right = addNode(5);
        root.left.left.right = addNode(2);
        root.right = addNode(3);
        root.right.right = addNode(8);
        root.right.right.left = addNode(6);
        root.right.right.right = addNode(7);
 
        // variable to store sum
        // of right leaves
        sum = 0;
        rightLeafSum(root);
        Console.WriteLine(sum);
    }
}
 
//  This code is contributed by Shrikant13


Javascript




<script>
    // Javascript program to find total
    // sum of right leaf nodes
     
    // sum
    let sum = 0;
     
    // node of binary tree
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    // return new node
    function addNode(data)
    {
        let temp = new Node(data);
        return temp;
    }
 
    // utility function to calculate
    // sum of right leaf nodes
    function rightLeafSum(root)
    {
        if(root == null)
            return;
 
        // check if the right child
        // of root is leaf node
        if(root.right != null)
            if(root.right.left == null &&
               root.right.right == null)
                sum += root.right.data;
 
        rightLeafSum(root.left);
        rightLeafSum(root.right);
    }
     
    //construct binary tree
    let root = addNode(1);
    root.left = addNode(2);
    root.left.left = addNode(4);
    root.left.right = addNode(5);
    root.left.left.right = addNode(2);
    root.right = addNode(3);
    root.right.right = addNode(8);
    root.right.right.left = addNode(6);
    root.right.right.right = addNode(7);
      
    // variable to store sum
    // of right leaves
    sum = 0;
    rightLeafSum(root);
    document.write(sum );
     
    // This code is contributed by divyesh072019.
</script>


Output

14

Time Complexity: O(n), As we are visiting every node.
Auxiliary Space: O(h), Here h is height of the tree and the extra space is used due to recursion call stack.

Another Method:

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. For right node we pass it as true, and false for left node. Time Complexity of this method is also O(n).

C++




// C++ program to find total sum of right leaf nodes.
#include <bits/stdc++.h>
using namespace std;
 
// struct node of Binary Tree
struct Node {
    int data;
    Node *left, *right;
};
 
// fun to create and return a new node
Node* addNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// fun to calculate sum of right leaf nodes
int rightLeafSum(Node* root, bool isrightleaf)
{
    // base case
    if (!root)
        return 0;
 
    // if it is a leaf node and right node, the return
    // root's data.
    if (!root->left && !root->right && isrightleaf)
        return root->data;
 
    // recur of left subtree and right subtree and do the
    // summation simultaniously.
    return rightLeafSum(root->left, false)
           + rightLeafSum(root->right, true);
}
 
int main()
{
    // create a tree
    Node* root = addNode(1);
    root->left = addNode(2);
    root->left->left = addNode(4);
    root->left->right = addNode(5);
    root->left->left->right = addNode(2);
    root->right = addNode(3);
    root->right->right = addNode(8);
    root->right->right->left = addNode(6);
    root->right->right->right = addNode(7);
 
    cout << rightLeafSum(root, false);
 
    return 0;
}
// This code is contributed by Modem Upendra


Java




// Java program to find total sum of right leaf nodes.
import java.util.*;
 
public class GFG {
 
  // structure of node of Binary Tree
  static class Node {
    int data;
    Node left, right;
 
    Node(int item)
    {
      data = item;
      left = right = null;
    }
  }
 
  // fun to calculate sum of right leaf nodes
  static int rightLeafSum(Node root, boolean isrightleaf)
  {
    // base case
    if (root == null)
      return 0;
 
    // if it is a leaf node and right node, the return
    // root's data.
    if (root.left == null && root.right == null
        && isrightleaf)
      return root.data;
 
    // recur of left subtree and right subtree and do
    // the summation simultaniously.
    return rightLeafSum(root.left, false)
      + rightLeafSum(root.right, true);
  }
  public static void main(String[] args)
  {
     
    // create a tree
    Node root = new Node(1);
    root.left = new Node(2);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.left.left.right = new Node(2);
    root.right = new Node(3);
    root.right.right = new Node(8);
    root.right.right.left = new Node(6);
    root.right.right.right = new Node(7);
 
    System.out.println(rightLeafSum(root, false));
  }
}
 
// This code is contributed by Karandeep1234


Python3




# Python code for the above approach
# Class of the tree Node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
def addNode(data):
    temp = Node(data)
    return temp
   
# fun to calculate sum of right leaf nodes
def rightLeafSum(root, isrightleaf):
    # base case
    if not root:
        return 0
       
# if it is a leaf node and right node, the return
# root's data.
    if not root.left and not root.right and isrightleaf:
        return root.data
     
    #recur of left subtree and right subtree and do
    # the summation simultaniously.
    return rightLeafSum(root.left, False) + rightLeafSum(root.right, True)
 
if __name__ == "__main__":
   
    # create a tree
    root = addNode(1)
    root.left = addNode(2)
    root.left.left = addNode(4)
    root.left.right = addNode(5)
    root.left.left.right = addNode(2)
    root.right = addNode(3)
    root.right.right = addNode(8)
    root.right.right.left = addNode(6)
    root.right.right.right = addNode(7)
 
    print(rightLeafSum(root, False))
 
# This code is contributed by lokeshpotta20.


C#




// C# program to find total sum of right leaf nodes.
 
using System;
 
public class GFG {
 
  // structure of node of Binary Tree
  public class Node {
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
      data = item;
      left = right = null;
    }
  }
 
  // fun to calculate sum of right leaf nodes
  static int rightLeafSum(Node root, bool isrightleaf)
  {
    // base case
    if (root == null)
      return 0;
 
    // if it is a leaf node and right node, the return
    // root's data.
    if (root.left == null && root.right == null
        && isrightleaf)
      return root.data;
 
    // recur of left subtree and right subtree and do
    // the summation simultaniously.
    return rightLeafSum(root.left, false)
      + rightLeafSum(root.right, true);
  }
  public static void Main(string[] args)
  {
 
    // create a tree
    Node root = new Node(1);
    root.left = new Node(2);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.left.left.right = new Node(2);
    root.right = new Node(3);
    root.right.right = new Node(8);
    root.right.right.left = new Node(6);
    root.right.right.right = new Node(7);
 
    Console.WriteLine(rightLeafSum(root, false));
  }
}
 
// This Code is contributed by karandeep1234


Javascript




// Javascript program to find total sum of right leaf nodes.
 
// struct node of Binary Tree
class Node {
    constructor(data)
    {
        this.data=data;
        this.left=null;
        this.right=null;
    }
};
 
/*// fun to create and return a new node
 addNode(int data)
{
    Node* temp = new Node();
    temp.data = data;
    temp.left = temp.right = NULL;
    return temp;
}*/
 
// fun to calculate sum of right leaf nodes
function rightLeafSum(root, isrightleaf)
{
    // base case
    if (!root)
        return 0;
 
    // if it is a leaf node and right node, the return
    // root's data.
    if (!root.left && !root.right && isrightleaf)
        return root.data;
 
    // recur of left subtree and right subtree and do the
    // summation simultaniously.
    return rightLeafSum(root.left, false)
           + rightLeafSum(root.right, true);
}
 
    // create a tree
    let root = new Node(1);
    root.left = new Node(2);
    root.left.left = new Node(4);
    root.left.right = new Node(5);
    root.left.left.right = new Node(2);
    root.right = new Node(3);
    root.right.right = new Node(8);
    root.right.right.left = new Node(6);
    root.right.right.right = new Node(7);
 
    console.log(rightLeafSum(root, false));
 
   // This code is contributed by poojaagarwal2.


Output

14

Time Complexity: O(n), As we are visiting every node.
Auxiliary Space: O(h), Here h is height of the tree and extra space is used dur to recursion call stack.

Method 2: Iterative Method

The above approach can be done with the help of a queue. The idea is to traverse the tree and whenever we reach the right node check if it is a leaf node. If it is a leaf node then increment the sum.

Implementation:

C++




// CPP program to find total sum
// of right leaf nodes
#include <bits/stdc++.h>
using namespace std;
 
// struct node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
 
// return new node
Node* addNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// utility function to calculate sum
// of right leaf nodes iteratively
int rightLeafSum(Node* root)
{
    // declaring sum to store sum of right leaves
    int sum = 0;
 
    // queue of Node* type
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();
        // check for left node
        if (curr->left) {
            q.push(curr->left);
        }
        // check for right node
        if (curr->right) {
 
            // check for right leaf node
            if (curr->right->right == NULL
                and curr->right->left == NULL) {
                // incrementing sum for found right leaf
                // node
                sum += curr->right->data;
            }
            q.push(curr->right);
        }
    }
    return sum;
}
 
// driver program
int main()
{
 
    // construct binary tree
    Node* root = addNode(1);
    root->left = addNode(2);
    root->left->left = addNode(4);
    root->left->right = addNode(5);
    root->left->left->right = addNode(2);
    root->right = addNode(3);
    root->right->right = addNode(8);
    root->right->right->left = addNode(6);
    root->right->right->right = addNode(7);
 
    int sum = rightLeafSum(root);
    cout << sum << endl;
    return 0;
}


Java




// Java program to find total sum
// of right leaf nodes
import java.io.*;
import java.util.*;
 
class Node {
    int data;
    Node left, right;
 
    Node(int data)
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}
 
class GFG {
 
    // return new node
    static Node addNode(int data)
    {
        Node temp = new Node(data);
        return temp;
    }
 
    // utility function to calculate sum
    // of right leaf nodes iteratively
    static int rightLeafSum(Node root)
    {
 
        // declaring sum to store sum of right leaves
        int sum = 0;
 
        // queue of Node* type
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        while (q.size() > 0) {
            Node curr = q.peek();
            q.remove();
 
            // check for left node
            if (curr.left != null) {
                q.add(curr.left);
            }
 
            // check for right node
            if (curr.right != null) {
 
                // check for right leaf node
                if (curr.right.right == null
                    && curr.right.left == null) {
 
                    // incrementing sum for found right leaf
                    // node
                    sum += curr.right.data;
                }
                q.add(curr.right);
            }
        }
        return sum;
    }
 
    // construct binary tree
    public static void main(String[] args)
    {
        Node root = addNode(1);
        root.left = addNode(2);
        root.left.left = addNode(4);
        root.left.right = addNode(5);
        root.left.left.right = addNode(2);
        root.right = addNode(3);
        root.right.right = addNode(8);
        root.right.right.left = addNode(6);
        root.right.right.right = addNode(7);
 
        int sum = rightLeafSum(root);
        System.out.println(sum);
    }
}
 
// This code is contributed by avanitrachhadiya2155.


Python3




# Python3 program to find total sum
# of right leaf nodes
 
# Return new node
 
 
class addNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Utility function to calculate Sum
# of right leaf nodes
def rightLeafSum(root):
    # Declaring sum to store sum of right leaves
    sum = 0
 
    # Queue of Node* type
    q = []
    q.append(root)
    while (len(q) > 0):
        curr = q.pop(0)
 
        # Check for left node
        if (curr.left != None):
            q.append(curr.left)
 
        # Check for right node
        if (curr.right != None):
            # Check for right leaf node
            if (curr.right.right == None and curr.right.left == None):
                # Incrementing sum for found right leaf
                # node
                sum += curr.right.data
 
            q.append(curr.right)
 
    return sum
 
 
# Driver Code
if __name__ == '__main__':
 
    # construct binary tree
    root = addNode(1)
    root.left = addNode(2)
    root.left.left = addNode(4)
    root.left.right = addNode(5)
    root.left.left.right = addNode(2)
    root.right = addNode(3)
    root.right.right = addNode(8)
    root.right.right.left = addNode(6)
    root.right.right.right = addNode(7)
 
    # variable to store Sum of right
    # leaves
    sum = rightLeafSum(root)
    print(sum)
 
# This code is contributed by Abhijeet Kumar(abhijeet19403)


C#




// C# program to find total sum
// of right leaf nodes
 
using System;
using System.Collections.Generic;
 
public
 
    class Node {
    public
 
        int data;
    public
 
        Node left,
        right;
 
    public
 
        Node(int data)
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}
 
public class GFG {
 
    // return new node
    static Node addNode(int data)
    {
        Node temp = new Node(data);
        return temp;
    }
 
    // utility function to calculate sum
    // of right leaf nodes iteratively
    static int rightLeafSum(Node root)
    {
 
        // declaring sum to store sum of right leaves
        int sum = 0;
 
        // queue of Node* type
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        while (q.Count > 0) {
            Node curr = q.Peek();
            q.Dequeue();
 
            // check for left node
            if (curr.left != null) {
                q.Enqueue(curr.left);
            }
 
            // check for right node
            if (curr.right != null) {
 
                // check for right leaf node
                if (curr.right.right == null
                    && curr.right.left == null) {
 
                    // incrementing sum for found right leaf
                    // node
                    sum += curr.right.data;
                }
                q.Enqueue(curr.right);
            }
        }
        return sum;
    }
 
    // construct binary tree
    public static void Main(String[] args)
    {
        Node root = addNode(1);
        root.left = addNode(2);
        root.left.left = addNode(4);
        root.left.right = addNode(5);
        root.left.left.right = addNode(2);
        root.right = addNode(3);
        root.right.right = addNode(8);
        root.right.right.left = addNode(6);
        root.right.right.right = addNode(7);
 
        int sum = rightLeafSum(root);
        Console.WriteLine(sum);
    }
}
 
// This code is contributed by umadevi9616


Javascript




<script>
 
    // JavaScript program to find total sum
    // of right leaf nodes
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    // return new node
    function addNode(data)
    {
        let temp = new Node(data);
        return temp;
    }
 
    // utility function to calculate sum
    // of right leaf nodes iteratively
    function rightLeafSum(root)
    {
        // declaring sum to store sum of right leaves
        let sum = 0;
 
        // queue of Node* type
        let q = [];
        q.push(root);
        while (q.length > 0) {
            let curr = q[0];
            q.shift();
            // check for left node
            if (curr.left != null) {
                q.push(curr.left);
            }
            // check for right node
            if (curr.right) {
 
                // check for right leaf node
                if (curr.right.right == null
                    && curr.right.left == null) {
                    // incrementing sum for found right leaf
                    // node
                    sum += curr.right.data;
                }
                q.push(curr.right);
            }
        }
        return sum;
    }
     
    // construct binary tree
    let root = addNode(1);
    root.left = addNode(2);
    root.left.left = addNode(4);
    root.left.right = addNode(5);
    root.left.left.right = addNode(2);
    root.right = addNode(3);
    root.right.right = addNode(8);
    root.right.right.left = addNode(6);
    root.right.right.right = addNode(7);
  
    let sum = rightLeafSum(root);
    document.write(sum);
 
</script>


Output

14

Time Complexity: O(n), As we are visiting every node.
Auxiliary Space: O(b), Here b is breadth of the tree and the extra space is used due to storing of the elements in the queue.

Another Iterative Approach(using Stack):
Follow the below steps to solve this problem:
1) Initialize a stack and perform any traversal(Inorder, Preorder or Postorder).
2) check for every node if right of that node is not null and a leaf node that add this node data into sum variable.
3) return sum.

Below is the implementation of above approach:

C++




// C++ program to find sum of all right leaves
#include<bits/stdc++.h>
using namespace std;
  
// A binary tree node
struct Node{
    int data;
    Node* left, *right;
    // A constructor to create a new Node
    Node(int key){
        data = key;
        left = NULL;
        right = NULL;
    }
};
  
// Return the sum of right leaf nodes
int sumOfRightLeaves(Node* root){
    if(root == NULL)
        return 0;
         
    // Using a stack_ for Depth-First
    // Traversal of the tree
    stack<Node*> st;
    st.push(root);
      
    // sum holds the sum of all the left leaves
    int sum = 0;
    while(st.size() > 0){
        Node* currentNode = st.top();
        st.pop();
  
        if (currentNode->right != NULL){
            st.push(currentNode->right);
            // Check if currentNode's left
            // child is a leaf node
            if(currentNode->right->left == NULL &&
               currentNode->right->right == NULL){
                // if currentNode is a leaf,
                // add its data to the sum
                sum = sum + currentNode->right->data ;
            }
        }
        if (currentNode->left != NULL)
            st.push(currentNode->left);
    }
    return sum;
}
  
// Driver Code to test above function
int main(){
    Node *root = new Node(1);
    root->left= new Node(2);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->left->left->right = new Node(2);
    root->right = new Node(3);
    root->right->right = new Node(8);
    root->right->right->left = new Node(6);
    root->right->right->right = new Node(7);
      
    cout << "Sum of right leaves is : "<<sumOfRightLeaves(root)<<endl;
    return 0;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Java




// Java Program to get intersection point of two linked list
import java.io.*;
import java.util.*;
 
public class BinaryTree{
    static class Node{
        int data;
        Node left;
        Node right;
        Node(int d){
            data = d;
            left = null;
            right = null;
        }
    }
     
    static int sumOfRightLeaves(Node root){
        if(root == null) return 0;
         
        // using a stack_ for depth first
        // traversal of the tree
        Stack<Node> st = new Stack<Node>();
        st.push(root);
         
        // sum holds the sum of all the left leaves
        int sum = 0;
        while(!st.isEmpty()){
            Node currentNode = st.pop();
            if(currentNode.right != null){
                st.push(currentNode.right);
                // check if currentNode's left
                // child is a leaf node
                if(currentNode.right.left == null && currentNode.right.right == null){
                    sum = sum + currentNode.right.data;
                }
            }
            if(currentNode.left != null){
                st.push(currentNode.left);
            }
        }
        return sum;
    }
     
    public static void main(String[] args){
        Node root = new Node(1);
        root.left = new Node(2);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.right = new Node(2);
        root.right = new Node(3);
        root.right.right = new Node(8);
        root.right.right.left = new Node(6);
        root.right.right.right = new Node(7);
         
        System.out.print("Sum of right leaves is : " + sumOfRightLeaves(root));
    }
}


Python




# Python program to find sum of all right leaves
# a binary tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
         
# return the sum of right leaf nodes
def sumOfRightLeaves(root):
    if(root is None):
        return 0
       
    # using a stack for depth first
    # traversal of the tree
    st = []
    st.append(root)
     
    # sum holds the sum of all the left leaves
    sum = 0
    while(len(st) > 0):
        currentNode = st.pop(0)
         
        if(currentNode.right is not None):
            st.append(currentNode.right)
             
            # check if currentnode's left
            # child is a leaf node
            if(currentNode.right.left is None and currentNode.right.right is None):
                # if currentNode is a leaf,
                # add its data to the sum
                sum = sum + currentNode.right.data
                 
        if(currentNode.left is not None):
            st.append(currentNode.left)
    return sum
 
 
# driver code to test above function
root = Node(1)
root.left = Node(2)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.left.right = Node(2)
root.right = Node(3)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
 
print("Sum of right leaves is : ")
print(sumOfRightLeaves(root))


C#




// C# Program to find sum of all right leaves
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL
using System;
using System.Collections.Generic;
 
// a binary tree node
public class Node{
    public int data;
    public Node left, right;
    // a constructor to create a new node
    public Node(int key){
        data = key;
        left = null;
        right = null;
    }
}
 
class GFG{
    // return the sum of right leaf nodes
    static int sumOfRightLeaves(Node root){
        if(root == null) return 0;
         
        // using a stack_ for depth first
        // traversal of the tree
        Stack<Node> st = new Stack<Node>();
        st.Push(root);
         
        // sum holds the sum of all the left leaves
        int sum = 0;
        while(st.Count > 0){
            Node currentNode = st.Pop();
            if(currentNode.right != null){
                st.Push(currentNode.right);
                // check if currentNode left
                // child is a leaf node
                if(currentNode.right.left == null && currentNode.right.right == null){
                    // if currentNode is a leaf
                    // node add its data to the sum
                    sum += currentNode.right.data;
                }
            }
            if(currentNode.left != null){
                st.Push(currentNode.left);
            }
        }
        return sum;
    }
     
    // driver code to test above function
    public static void Main(String[] args){
        Node root = new Node(1);
        root.left = new Node(2);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.left.left.right = new Node(2);
        root.right = new Node(3);
        root.right.right = new Node(8);
        root.right.right.left = new Node(6);
        root.right.right.right = new Node(7);
         
        Console.WriteLine("Sum of right leaves is : " + sumOfRightLeaves(root));
    }
}


Javascript




// Javascript program to find sum of all right leaves
// a binary tree node
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// return the sum of right leaf nodes
function sumOfRightLeaves(root){
    if(root == null) return 0;
     
    // using a stack_for depth first search
    // traversal of the tree
    let st = [];
    st.push(root);
     
    // sum holds the sum of all the left leaves
    let sum = 0;
    while(st.length > 0){
        let currentNode = st.pop();
        if(currentNode.right != null){
            st.push(currentNode.right);
             
            // check if currentnode's left
            // child is a leaf node
            if(currentNode.right.left == null && currentNode.right.right == null){
                sum = sum + currentNode.right.data;
            }
        }
        if(currentNode.left != null)
            st.push(currentNode.left);
    }
    return sum;
}
 
// driver code to test above function
let root = new Node(1);
root.left= new Node(2);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.left.right = new Node(2);
root.right = new Node(3);
root.right.right = new Node(8);
root.right.right.left = new Node(6);
root.right.right.right = new Node(7);
 
console.log("Sum of right leaves is : " + sumOfRightLeaves(root));


Output

Sum of right leaves is : 14

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to stack data structure.

 

This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


My Personal Notes arrow_drop_up
Last Updated : 15 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials