VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-program-to-print-right-view-of-binary-tree/

⇱ JavaScript Program to Print Right View of Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript Program to Print Right View of Binary Tree

Last Updated : 3 May, 2024

The right view of a binary tree refers to the nodes visible when viewed from the right side of the tree. There are multiple approaches to print the right view of a binary tree, each with its own advantages and complexities. In this article, we'll explore two approaches-

Examples:

Input:
5
/ \
4 6
/ \ / \
5 2 1 3

Output: Right view of the tree is 5 6 3

Input:
5
/
3
/
1

Output: Right view of the tree is 5 3 1

Using Recursion

In this approach, we recursively traverse the binary tree while maintaining the current level and the maximum level reached so far. At each level, we only consider the right child if it is the first node encountered at that level. This ensures that the right view includes only the rightmost node at each level.

Example: Implementation to show right view of binary tree using recursion approach.


Output
[ 1, 3, 6 ]

Time Complexity: O(n)

Space Complexity: O(n)

Using Level Order Traversal

Using this approach, we traverse the binary tree in level-order, also known as breadth-first search (BFS). At each level, we keep track of the last node encountered and append it to the result array. This ensures that the right view includes only the rightmost node at each level.

Example: Implementation to show right view of binary tree using level order transversal.


Output
[ 1, 3, 6 ]

Time Complexity: O(n)

Space Complexity: O(n)

Comment