You are given the root
of a binary tree. Imagine yourself standing on the right side of it; you should return the values of the nodes you can see ordered from top to bottom.
The strategy to solve this problem can be broken down into the following steps:
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def rightSideView(root: TreeNode) -> list[int]:
if not root:
return []
right_view = []
queue = deque([root])
while queue:
level_length = len(queue)
for i in range(level_length):
node = queue.popleft()
if i == level_length - 1:
# the rightmost element of this level
right_view.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return right_view
The time complexity of this approach is O(N), where (N) is the number of nodes in the binary tree. This is because we’re visiting each node exactly once during the traversal.
The space complexity is also O(N) in the worst case. This is due to the queue used for the breadth-first search, which in the worst case can store up to half the number of nodes at the last level of a complete binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?