Given a binary tree, the task is to find the sum of the nodes which are visible in the right view. The right view of a binary tree is the set of nodes visible when the tree is viewed from the right.
Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 10 1 + 3 + 6 = 10 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: 19
Approach: The problem can be solved using simple recursive traversal. We can keep track of the level of a node by passing a parameter to all the recursive calls. The idea is to keep track of the maximum level also and traverse the tree in a manner that the right subtree is visited before the left subtree. Whenever a node whose level is more than the maximum level so far is encountered, add the value of the node to the sum because it is the last node in its level (Note that the right subtree is traversed before the left subtree).
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sum of nodes in the left view of the given binary tree
- Sum of nodes in top view of binary tree
- Sum of nodes in bottom view of Binary Tree
- Print Right View of a Binary Tree
- Print Bottom-Right View of a Binary Tree
- Right view of Binary Tree using Queue
- Print Nodes in Top View of Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Print nodes in top view of Binary Tree | Set 2
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Convert left-right representation of a binary tree to down-right
- Find maximum among all right nodes in Binary Tree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print leaf nodes in binary tree from left to right using one stack
- Print all leaf nodes of a binary tree from right to left
- Print left and right leaf nodes separately in Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count of all prime weight nodes between given nodes in the given Tree
- Find sum of all right leaves in a given Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.