Binary Tree Right Side View
- 1 min read
- LC-Medium
- Binary Tree
My Solution
- Do a Breadth-first Search, and at each level, before going through the queue, append the last element to answer
- Initially, I did this with an array which stores all the nodes in the array, but you don't need this.
| Time | Space | Explanation |
|---|
O(n) | O(n) | |
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
q = deque([root])
ans = []
while q:
ans.append(q[-1].val)
for _ in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return ans