Binary Tree Right Side View
Understand and solve the interview question "Binary Tree Right Side View".
We'll cover the following...
Description
You are given a binary tree T
. Imagine you are standing to the right of it; you have to return the value of the nodes you can see from top to bottom.
You have to return the rightmost nodes on their respective levels in the form of an array.
Let’s discuss an example below:
Coding exercise
index.js
TreeNode.js
import {TreeNode} from './TreeNode.js'function rightSideView(root){// write your code herereturn []}
Binary tree right side view
Solution
We can use a depth-first search (DFS) to solve this problem. The intuition here is to traverse the tree level by level recursively, starting from the rightmost
node for each recursive call.
Let’s review the implementation below:
index.js
TreeNode.js
import {TreeNode} from './TreeNode.js'function rightSideView(root){if (root == null)return []var rightside = []function DFS(node, level){if (level == rightside.length)rightside.push(node.val)temp = [node.right, node.left]temp.forEach((child) => {if (child != null)DFS(child, level + 1)})}DFS(root, 0)return rightside}// Driver Codevar root = new TreeNode(1)root.left = new TreeNode(2)root.right = new TreeNode(3)root.left.left = new TreeNode(4);root.left.right = new TreeNode(5);root.right.left = new TreeNode(6);root.right.right = new TreeNode(7);root.right.right.left = new TreeNode(8);console.log(rightSideView(root))
Binary tree right side view
Complexity measures
Time Complexity | Space |
---|