103. Binary Tree Zigzag Level Order Traversal
Tree, BFS, Binary Tree, AMateList ·Problem Statement
link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
Given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between).
Example:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
Solution Approach
The solution employs depth-first search (DFS) to traverse the tree and utilizes a deque to maintain the order of node values based on the current level of traversal.
Algorithm
- Using a recursive dfs function, traverse the tree nodes based on their depth level.
- Depending on the current level, either append or prepend the node’s value to the respective deque to achieve the zigzag order.
- Convert the list of deques into a list of lists after traversal to obtain the final zigzag level order result.
Implement
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
res = []
def dfs(node,level):
if not node:
return
# add node.val in level
if level < len(res):
if level % 2:
res[level].appendleft(node.val)
else:
res[level].append(node.val)
else:
res.append(deque([node.val]))
if node.left:
dfs(node.left, level + 1)
if node.right:
dfs(node.right, level + 1)
dfs(root, 0)
return [list(d) for d in res]