[Expected Approach - 1] Using Recursion - O(n) Time and O(h) Space
The idea is to use recursion 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.
Below is the implementation for the above approach:
C++
// C++ program to find sum of all right // leaf nodes in a binary tree#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intvalue){data=value;left=right=nullptr;}};// Recursive function to find the sum of // right leaf nodesvoidrightLeafSum(Node*root,int&sum){if(!root)return;// Check if the right child of root is a leaf nodeif(root->right&&!root->right->left&&!root->right->right){sum+=root->right->data;}// Recur for the left and right childrenrightLeafSum(root->left,sum);rightLeafSum(root->right,sum);}intmain(){// Representation of given the binary tree// 1// / \ // 2 3// \ \ // 5 8Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(5);root->right->right=newNode(8);intsum=0;rightLeafSum(root,sum);cout<<sum<<endl;return0;}
Java
// Java program to find sum of all right // leaf nodes in a binary treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=right=null;}}// Recursive function to find the sum of // right leaf nodesclassGfG{staticvoidrightLeafSum(Noderoot,int[]sum){if(root==null)return;// Check if the right child of root // is a leaf nodeif(root.right!=null&&root.right.left==null&&root.right.right==null){sum[0]+=root.right.data;}// Recur for the left and right childrenrightLeafSum(root.left,sum);rightLeafSum(root.right,sum);}publicstaticvoidmain(String[]args){// Representation of given the binary tree// 1// / \// 2 3// \ \// 5 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);int[]sum={0};rightLeafSum(root,sum);System.out.println(sum[0]);}}
Python
# Python program to find sum of all right # leaf nodes in a binary treeclassNode:def__init__(self,value):self.data=valueself.left=Noneself.right=None# Recursive function to find the sum of # right leaf nodesdefrightLeafSum(root,sum_ref):ifnotroot:return# Check if the right child of root# is a leaf nodeifroot.rightandnotroot.right.left \
andnotroot.right.right:sum_ref[0]+=root.right.data# Recur for the left and right childrenrightLeafSum(root.left,sum_ref)rightLeafSum(root.right,sum_ref)if__name__=='__main__':# Representation of given the binary tree# 1# / \# 2 3# \ \# 5 8root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(5)root.right.right=Node(8)sum_ref=[0]rightLeafSum(root,sum_ref)print(sum_ref[0])
C#
// C# program to find sum of all right // leaf nodes in a binary treeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intvalue){data=value;left=right=null;}}// Recursive function to find the sum of // right leaf nodesclassGfG{staticvoidRightLeafSum(Noderoot,refintsum){if(root==null)return;// Check if the right child of root // is a leaf nodeif(root.right!=null&&root.right.left==null&&root.right.right==null){sum+=root.right.data;}// Recur for the left and right childrenRightLeafSum(root.left,refsum);RightLeafSum(root.right,refsum);}staticvoidMain(string[]args){// Representation of given the binary tree// 1// / \// 2 3// \ \// 5 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);intsum=0;RightLeafSum(root,refsum);Console.WriteLine(sum);}}
JavaScript
// JavaScript program to find sum of all right // leaf nodes in a binary treeclassNode{constructor(value){this.data=value;this.left=null;this.right=null;}}// Recursive function to find the sum of // right leaf nodesfunctionrightLeafSum(root,sumRef){if(!root)return;// Check if the right child of root// is a leaf nodeif(root.right&&!root.right.left&&!root.right.right){sumRef.sum+=root.right.data;}// Recur for the left and // right childrenrightLeafSum(root.left,sumRef);rightLeafSum(root.right,sumRef);}// Representation of given the binary tree// 1// / \// 2 3// \ \// 5 8letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);letsumRef={sum:0};rightLeafSum(root,sumRef);console.log(sumRef.sum);
Output
13
[Alternate Approach] Using Recursion - O(n) Time and O(h) Space
Alternative idea to solve the above problem is that 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.
Below is the implementation for the above approach:
C++
// C++ program to find sum of all right // leaf nodes in a binary tree#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intvalue){data=value;left=right=nullptr;}};intrightLeafSum(Node*root,boolisrightleaf){// base caseif(!root)return0;// if it is a leaf node and right node, the return// root's data.if(!root->left&&!root->right&&isrightleaf)returnroot->data;// recur of left subtree and right subtree and do the// summation simultaniously.returnrightLeafSum(root->left,false)+rightLeafSum(root->right,true);}intmain(){// Representation of given the binary tree// 1// / \ // 2 3// \ \ // 5 8Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(5);root->right->right=newNode(8);boolisrightleaf=0;intsum=rightLeafSum(root,isrightleaf);cout<<sum<<endl;return0;}
Java
// Java program to find sum of all right // leaf nodes in a binary treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=right=null;}}classGfG{staticintrightLeafSum(Noderoot,booleanisRightLeaf){// base caseif(root==null)return0;// if it is a leaf node and right node, // return root's dataif(root.left==null&&root.right==null&&isRightLeaf)returnroot.data;// recur on left subtree and right subtree // and do the summation simultaneouslyreturnrightLeafSum(root.left,false)+rightLeafSum(root.right,true);}publicstaticvoidmain(String[]args){// Representation of the given binary tree// 1// / \// 2 3// \ \// 5 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);intsum=rightLeafSum(root,false);System.out.println(sum);}}
Python
# Python program to find sum of all right # leaf nodes in a binary treeclassNode:def__init__(self,value):self.data=valueself.left=Noneself.right=Nonedefrightleafsum(root,isrightleaf):# base caseifnotroot:return0# if it is a leaf node and right node, # return root's dataifnotroot.leftandnotroot.right\
andisrightleaf:returnroot.data# recur on left subtree and right subtree # and do the summation simultaneouslyreturnrightleafsum(root.left,False) \
+rightleafsum(root.right,True)if__name__=='__main__':# Representation of the given binary tree# 1# / \# 2 3# \ \# 5 8root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(5)root.right.right=Node(8)sumResult=rightleafsum(root,False)print(sumResult)
C#
// C# program to find sum of all right // leaf nodes in a binary treeusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intvalue){data=value;left=right=null;}}classGfG{staticintRightLeafSum(Noderoot,boolisRightLeaf){// base caseif(root==null)return0;// if it is a leaf node and right node,// return root's dataif(root.left==null&&root.right==null&&isRightLeaf)returnroot.data;// recur on left subtree and right subtree // and do the summation simultaneouslyreturnRightLeafSum(root.left,false)+RightLeafSum(root.right,true);}staticvoidMain(string[]args){// Representation of the given binary tree// 1// / \// 2 3// \ \// 5 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);intsum=RightLeafSum(root,false);Console.WriteLine(sum);}}
JavaScript
// JavaScript program to find sum of all right // leaf nodes in a binary treeclassNode{constructor(value){this.data=value;this.left=null;this.right=null;}}functionrightLeafSum(root,isRightLeaf){// base caseif(!root)return0;// if it is a leaf node and right node, // return root's dataif(!root.left&&!root.right&&isRightLeaf)returnroot.data;// recur on left subtree and right subtree // and do the summation simultaneouslyreturnrightLeafSum(root.left,false)+rightLeafSum(root.right,true);}// Representation of the given binary tree// 1// / \// 2 3// \ \// 5 8letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);letsum=rightLeafSum(root,false);console.log(sum);
Output
13
[Expected Approach - 2] Using Iterative Method - O(n) Time and O(n) Space
The idea is to traverse the tree in level order manner using queue and whenever we reach the right node check if it is a leaf node. If it is a leaf node then increment the sum.
Below is the implementation for the above approach:
C++
// C++ program to find sum of all right // leaf nodes in a binary tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intvalue){data=value;left=right=nullptr;}};// Utility function to calculate sum// of right leaf nodes iterativelyintrightLeafSum(Node*root){// Declaring sum to store sum // of right leavesintsum=0;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();// Check for left nodeif(curr->left){q.push(curr->left);}// Check for right nodeif(curr->right){// Check for right leaf nodeif(curr->right->right==nullptrandcurr->right->left==nullptr){// incrementing sum for found right leaf// nodesum+=curr->right->data;}q.push(curr->right);}}returnsum;}intmain(){// Representation of given the binary tree// 1// / \ // 2 3// \ \ // 5 8Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->right=newNode(5);root->right->right=newNode(8);intsum=rightLeafSum(root);cout<<sum<<endl;return0;}
Java
// Java program to find sum of all right // leaf nodes in a binary treeimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=right=null;}}classGfG{// Utility function to calculate sum of right // leaf nodes iterativelystaticintrightLeafSum(Noderoot){// Declaring sum to store sum of right leavesintsum=0;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){Nodecurr=q.poll();// Check for left nodeif(curr.left!=null){q.add(curr.left);}// Check for right nodeif(curr.right!=null){// Check for right leaf nodeif(curr.right.left==null&&curr.right.right==null){// incrementing sum for found// right leaf nodesum+=curr.right.data;}q.add(curr.right);}}returnsum;}publicstaticvoidmain(String[]args){// Representation of given the binary tree// 1// / \// 2 3// \ \// 5 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);intsum=rightLeafSum(root);System.out.println(sum);}}
Python
# Python program to find sum of all right # leaf nodes in a binary treefromcollectionsimportdequeclassNode:def__init__(self,value):self.data=valueself.left=Noneself.right=None# Utility function to calculate sum of # right leaf nodes iterativelydefright_leaf_sum(root):# Declaring sum to store sum of# right leavessum=0q=deque([root])whileq:curr=q.popleft()# Check for left nodeifcurr.left:q.append(curr.left)# Check for right nodeifcurr.right:# Check for right leaf nodeifcurr.right.leftisNone \
andcurr.right.rightisNone:# incrementing sum for found# right leaf nodesum+=curr.right.dataq.append(curr.right)returnsumif__name__=='__main__':# Representation of given the binary tree# 1# / \# 2 3# \ \# 5 8root=Node(1)root.left=Node(2)root.right=Node(3)root.left.right=Node(5)root.right.right=Node(8)sum_result=right_leaf_sum(root)print(sum_result)
C#
// C# program to find sum of all right // leaf nodes in a binary treeusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intvalue){data=value;left=right=null;}}classGfG{// Utility function to calculate sum of // right leaf nodes iterativelystaticintRightLeafSum(Noderoot){// Declaring sum to store sum of// right leavesintsum=0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();// Check for left nodeif(curr.left!=null){q.Enqueue(curr.left);}// Check for right nodeif(curr.right!=null){// Check for right leaf nodeif(curr.right.left==null&&curr.right.right==null){// incrementing sum for // found right leaf nodesum+=curr.right.data;}q.Enqueue(curr.right);}}returnsum;}staticvoidMain(string[]args){// Representation of given the binary tree// 1// / \// 2 3// \ \// 5 8Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);intsum=RightLeafSum(root);Console.WriteLine(sum);}}
JavaScript
// JavaScript program to find sum of all right // leaf nodes in a binary treeclassNode{constructor(value){this.data=value;this.left=null;this.right=null;}}// Utility function to calculate sum of // right leaf nodes iterativelyfunctionrightLeafSum(root){// Declaring sum to store sum // of right leavesletsum=0;constq=[root];while(q.length>0){constcurr=q.shift();// Check for left nodeif(curr.left){q.push(curr.left);}// Check for right nodeif(curr.right){// Check for right leaf nodeif(!curr.right.left&&!curr.right.right){// incrementing sum for found // right leaf nodesum+=curr.right.data;}q.push(curr.right);}}returnsum;}// Representation of given the binary tree// 1// / \// 2 3// \ \// 5 8constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.right=newNode(5);root.right.right=newNode(8);constsum=rightLeafSum(root);console.log(sum);