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
main.java
TreeNode.java
class Solution {public static List<Integer> rightSideView(TreeNode root) {// write your code herereturn new ArrayList<Integer>();}}
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:
main.java
TreeNode.java
class Solution {public static void DFS(TreeNode node, int level, List<Integer> rightside) {if (level == rightside.size())rightside.add(node.val);if (node.right != null)DFS(node.right, level + 1, rightside);if (node.left != null)DFS(node.left, level + 1, rightside);}public static List<Integer> rightSideView(TreeNode root) {List<Integer> rightside = new ArrayList<Integer>();if (root == null) return rightside;DFS(root, 0, rightside);return rightside;}public static void main(String args[]){TreeNode 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);System.out.println("" + rightSideView(root));}}
Binary tree right side view
Complexity measures
Time Complexity |
---|