Given the root of a binary tree root, return an array with the the "right side view" of the tree.
Example:
rightSideView(TreeNode.of([1]))
# [1]rightSideView(TreeNode.of([1, 2, 3]))
# [1, 3]rightSideView(TreeNode.of([1, 2, 3, 4, 5, None, 6]))
# [1, 3, 6]We can't do a greedy solution that just goes down the rightmost branch, because that branch might end, exposing other branches. We need to traverse the tree layer-by-layer, taking the rightmost node at each layer.
We should use a BFS since a BFS goes layer-by-layer naturally. Here's the code for a BFS from the lesson:
queue = deque([root])
while queue:
# loop through all the nodes in the current layer together
for _ in range(len(queue)):
node = queue.popleft()
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)Now, how do we find the rightmost node in each layer of the BFS?
Remember that the line for _ in range(len(queue)) visits nodes layer by layer.
For example, here's what the queue looks like after visiting the 1st layer:
And here's what it looks like after visiting the 2nd layer:
The rightmost node is always the last element in the queue, queue[-1]. So to solve the problem, we'll keep an array of all the rightmost nodes we've seen so far in an array, called soln. We just stick a few lines of code into the BFS:
from collections import deque
def rightSideView(root):
soln = [] # array with rightmost values
queue = deque([root])
while queue:
soln.append(queue[-1].val) # append rightmost value to array before visiting next layer
for _ in range(len(queue)):
node = queue.popleft()
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return soln