I'm trying to solve LeetCode 199.
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
I've already solved this problem by using Level-Order-Traversal with time complexity of O(n) & memory complexity of O(n).
I'm wondering if it's possible to optimize the solution, and solve this problem iteratively with constant memory complexity of O(1) without using any data structure.
My solution with time & memory of O(n):
# 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
class Solution:
# time complexity: O(n), memory complexity: O(n)
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if not root: return []
res = []
q = collections.deque([root])
while q:
len_q, level = len(q), []
for _ in range(len_q):
node = q.popleft()
level.append(node)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
res.append(level[-1].val) # add the last element of each level (right most element)
return res