For a tree travesal problem, we have two approaches to takle it: BFS and DFS.
For a BFS, we just use a queue, it is the same as 102. Binary Tree Level Order Traversal, the code is following:
res = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
res.append(node.val)
queue.extend([node.left, node.right])
return res
By changing the queue
to stack
, it will naturally give us DFS search. This corresponds to reorder:
res = []
stack = [root]
while stack:
node = stack.pop()
if node:
stack.extend([node.right, node.left])
res.append(node.val)
return res