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.rb
TreeNode.rb
require './TreeNode.rb'
def right_side_view(root)
# write your code here
end
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.rb
TreeNode.rb
require './TreeNode.rb'
def right_side_view(root)
if root == nil
return []
end
rightside = []
def DFS(node, level, rightside)
if level == rightside.length()
rightside.push(node.val)
end
[node.right, node.left].each do |child|
if child
DFS(child, level + 1, rightside)
end
end
end
DFS(root, 0, rightside)
return rightside
end
# Driver Code
root = TreeNode.new(1)
root.left = TreeNode.new(2)
root.right = TreeNode.new(3)
root.left.left = TreeNode.new(4);
root.left.right = TreeNode.new(5);
root.right.left = TreeNode.new(6);
root.right.right = TreeNode.new(7);
root.right.right.left = TreeNode.new(8);
p(right_side_view(root))
Binary tree right side view

Complexity measures

Time Complexity Space
...