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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* addNode( int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
void rightLeafSum(Node* root, int & sum)
{
if (!root)
return ;
if (root->right)
if (root->right->left == NULL
&& root->right->right == NULL)
sum += root->right->data;
rightLeafSum(root->left, sum);
rightLeafSum(root->right, sum);
}
int main()
{
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 = 0;
rightLeafSum(root, sum);
cout << sum << endl;
return 0;
}
|
Java
class GFG {
static int sum = 0 ;
static class Node {
int data;
Node left, right;
};
static Node addNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
static void rightLeafSum(Node root)
{
if (root == null )
return ;
if (root.right != null )
if (root.right.left == null
&& root.right.right == null )
sum += root.right.data;
rightLeafSum(root.left);
rightLeafSum(root.right);
}
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 );
sum = 0 ;
rightLeafSum(root);
System.out.println(sum);
}
}
|
Python3
class addNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def rightLeafSum(root, Sum ):
if ( not root):
return
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 )
if __name__ = = '__main__' :
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 )
Sum = [ 0 ]
rightLeafSum(root, Sum )
print ( Sum [ 0 ])
|
C#
using System;
public class GFG {
public static int sum = 0;
public class Node {
public int data;
public Node left, right;
}
public static Node addNode( int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null ;
return temp;
}
public static void rightLeafSum(Node root)
{
if (root == null ) {
return ;
}
if (root.right != null ) {
if (root.right.left == null
&& root.right.right == null ) {
sum += root.right.data;
}
}
rightLeafSum(root.left);
rightLeafSum(root.right);
}
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);
sum = 0;
rightLeafSum(root);
Console.WriteLine(sum);
}
}
|
Javascript
<script>
let sum = 0;
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function addNode(data)
{
let temp = new Node(data);
return temp;
}
function rightLeafSum(root)
{
if (root == null )
return ;
if (root.right != null )
if (root.right.left == null &&
root.right.right == null )
sum += root.right.data;
rightLeafSum(root.left);
rightLeafSum(root.right);
}
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);
sum = 0;
rightLeafSum(root);
document.write(sum );
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* addNode( int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int rightLeafSum(Node* root, bool isrightleaf)
{
if (!root)
return 0;
if (!root->left && !root->right && isrightleaf)
return root->data;
return rightLeafSum(root->left, false )
+ rightLeafSum(root->right, true );
}
int main()
{
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;
}
|
Java
import java.util.*;
public class GFG {
static class Node {
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
static int rightLeafSum(Node root, boolean isrightleaf)
{
if (root == null )
return 0 ;
if (root.left == null && root.right == null
&& isrightleaf)
return root.data;
return rightLeafSum(root.left, false )
+ rightLeafSum(root.right, true );
}
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.println(rightLeafSum(root, false ));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def addNode(data):
temp = Node(data)
return temp
def rightLeafSum(root, isrightleaf):
if not root:
return 0
if not root.left and not root.right and isrightleaf:
return root.data
return rightLeafSum(root.left, False ) + rightLeafSum(root.right, True )
if __name__ = = "__main__" :
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 ))
|
C#
using System;
public class GFG {
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
static int rightLeafSum(Node root, bool isrightleaf)
{
if (root == null )
return 0;
if (root.left == null && root.right == null
&& isrightleaf)
return root.data;
return rightLeafSum(root.left, false )
+ rightLeafSum(root.right, true );
}
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(rightLeafSum(root, false ));
}
}
|
Javascript
class Node {
constructor(data)
{
this .data=data;
this .left= null ;
this .right= null ;
}
};
function rightLeafSum(root, isrightleaf)
{
if (!root)
return 0;
if (!root.left && !root.right && isrightleaf)
return root.data;
return rightLeafSum(root.left, false )
+ rightLeafSum(root.right, true );
}
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 ));
|
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* addNode( int data)
{
Node* temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
int rightLeafSum(Node* root)
{
int sum = 0;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* curr = q.front();
q.pop();
if (curr->left) {
q.push(curr->left);
}
if (curr->right) {
if (curr->right->right == NULL
and curr->right->left == NULL) {
sum += curr->right->data;
}
q.push(curr->right);
}
}
return sum;
}
int main()
{
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
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 {
static Node addNode( int data)
{
Node temp = new Node(data);
return temp;
}
static int rightLeafSum(Node root)
{
int sum = 0 ;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (q.size() > 0 ) {
Node curr = q.peek();
q.remove();
if (curr.left != null ) {
q.add(curr.left);
}
if (curr.right != null ) {
if (curr.right.right == null
&& curr.right.left == null ) {
sum += curr.right.data;
}
q.add(curr.right);
}
}
return sum;
}
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);
}
}
|
Python3
class addNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def rightLeafSum(root):
sum = 0
q = []
q.append(root)
while ( len (q) > 0 ):
curr = q.pop( 0 )
if (curr.left ! = None ):
q.append(curr.left)
if (curr.right ! = None ):
if (curr.right.right = = None and curr.right.left = = None ):
sum + = curr.right.data
q.append(curr.right)
return sum
if __name__ = = '__main__' :
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 )
sum = rightLeafSum(root)
print ( sum )
|
C#
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 {
static Node addNode( int data)
{
Node temp = new Node(data);
return temp;
}
static int rightLeafSum(Node root)
{
int sum = 0;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
Node curr = q.Peek();
q.Dequeue();
if (curr.left != null ) {
q.Enqueue(curr.left);
}
if (curr.right != null ) {
if (curr.right.right == null
&& curr.right.left == null ) {
sum += curr.right.data;
}
q.Enqueue(curr.right);
}
}
return sum;
}
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);
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function addNode(data)
{
let temp = new Node(data);
return temp;
}
function rightLeafSum(root)
{
let sum = 0;
let q = [];
q.push(root);
while (q.length > 0) {
let curr = q[0];
q.shift();
if (curr.left != null ) {
q.push(curr.left);
}
if (curr.right) {
if (curr.right.right == null
&& curr.right.left == null ) {
sum += curr.right.data;
}
q.push(curr.right);
}
}
return sum;
}
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>
|
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++
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* left, *right;
Node( int key){
data = key;
left = NULL;
right = NULL;
}
};
int sumOfRightLeaves(Node* root){
if (root == NULL)
return 0;
stack<Node*> st;
st.push(root);
int sum = 0;
while (st.size() > 0){
Node* currentNode = st.top();
st.pop();
if (currentNode->right != NULL){
st.push(currentNode->right);
if (currentNode->right->left == NULL &&
currentNode->right->right == NULL){
sum = sum + currentNode->right->data ;
}
}
if (currentNode->left != NULL)
st.push(currentNode->left);
}
return sum;
}
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;
}
|
Java
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 ;
Stack<Node> st = new Stack<Node>();
st.push(root);
int sum = 0 ;
while (!st.isEmpty()){
Node currentNode = st.pop();
if (currentNode.right != null ){
st.push(currentNode.right);
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
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def sumOfRightLeaves(root):
if (root is None ):
return 0
st = []
st.append(root)
sum = 0
while ( len (st) > 0 ):
currentNode = st.pop( 0 )
if (currentNode.right is not None ):
st.append(currentNode.right)
if (currentNode.right.left is None and currentNode.right.right is None ):
sum = sum + currentNode.right.data
if (currentNode.left is not None ):
st.append(currentNode.left)
return sum
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#
using System;
using System.Collections.Generic;
public class Node{
public int data;
public Node left, right;
public Node( int key){
data = key;
left = null ;
right = null ;
}
}
class GFG{
static int sumOfRightLeaves(Node root){
if (root == null ) return 0;
Stack<Node> st = new Stack<Node>();
st.Push(root);
int sum = 0;
while (st.Count > 0){
Node currentNode = st.Pop();
if (currentNode.right != null ){
st.Push(currentNode.right);
if (currentNode.right.left == null && currentNode.right.right == null ){
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);
Console.WriteLine( "Sum of right leaves is : " + sumOfRightLeaves(root));
}
}
|
Javascript
class Node{
constructor(data){
this .data = data;
this .left = null ;
this .right = null ;
}
}
function sumOfRightLeaves(root){
if (root == null ) return 0;
let st = [];
st.push(root);
let sum = 0;
while (st.length > 0){
let currentNode = st.pop();
if (currentNode.right != null ){
st.push(currentNode.right);
if (currentNode.right.left == null && currentNode.right.right == null ){
sum = sum + currentNode.right.data;
}
}
if (currentNode.left != null )
st.push(currentNode.left);
}
return sum;
}
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));
|
OutputSum 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.