Binary Tree Right Side View

Understand and solve the interview question "Binary Tree Right Side View".

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.kt
TreeNode.kt
internal object Solution {
fun rightSideView(root: TreeNode?): List<Int> {
// write your code here
return ArrayList()
}
}
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.kt
TreeNode.kt
internal object Solution {
fun DFS(node: TreeNode, level: Int, rightside: ArrayList<Int>) {
if (level == rightside.size) rightside.add(node.`val`)
if (node.right != null) Solution.DFS(node.right!!, level + 1, rightside)
if (node.left != null) Solution.DFS(node.left!!, level + 1, rightside)
}
fun rightSideView(root: TreeNode?): List<Int> {
val rightside: ArrayList<Int> = ArrayList()
if (root == null) return rightside
Solution.DFS(root, 0, rightside)
return rightside
}
}
fun main() {
val root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left!!.left = TreeNode(4)
root.left!!.right = TreeNode(5)
root.right!!.left = TreeNode(6)
root.right!!.right = TreeNode(7)
root.right!!.right!!.left = TreeNode(8)
println("" + Solution.rightSideView(root))
}

Complexity measures

Time Complexity Space
...