VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sum-right-leaves-given-binary-tree/

⇱ Find sum of all right leaves in a given Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find sum of all right leaves in a given Binary Tree

Last Updated : 1 Nov, 2024

Given a Binary Tree, the task is to find the sum of all right leaf nodes in it.

Examples :

Example1: Sum of all the right leaf nodes in the below tree is 2 + 5 + 7 = 15

👁 find-sum-of-all-right-leaves-in-a-given-binary-tree


Example2: Sum of all the right leaf nodes in the below tree is 5 + 8 = 13

👁 find-sum-of-all-right-leaves-in-a-given-binary-tree-2

[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:


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:


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:


Output
13

Related article:

Comment
Article Tags: