Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is visited from Right side.
Right view of following tree is 1 3 7 8 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8
The Right view contains all nodes that are last nodes in their levels. A simple solution is to do level order traversal and print the last node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of level of a node by passing a parameter to all recursive calls. The idea is to keep track of maximum level also. And traverse the tree in a manner that right subtree is visited before left subtree. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the last node in its level (Note that we traverse the right subtree before left subtree). Following is the implementation of this approach.
1 3 7 8
Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n).
This article is contributed by Shalki Agarwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
- Print Bottom-Right View of a Binary Tree
- Sum of nodes in the right view of the given binary tree
- Right view of Binary Tree using Queue
- Convert left-right representation of a binary tree to down-right
- Print Nodes in Top View of Binary Tree
- Print nodes in the Top View of Binary Tree | Set 3
- Iterative Method To Print Left View of a Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- Print Left View of a 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
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Bottom View of a Binary Tree
- Sum of nodes in top view of binary tree
- Sum of nodes in the left view of the given binary tree
- Sum of nodes in bottom view of Binary Tree
- Bottom View of a Binary Tree using Recursion