Skip to content

Commit 5888cdb

Browse files
committed
problem: 0103 binary tree zigzag level order traversal
1 parent 0d910f7 commit 5888cdb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# 0103. Binary Tree Zigzag Level Order Traversal
2+
3+
* Difficulty: medium
4+
* Link: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
5+
* Topics: DFS-BFS
6+
7+
# Clarification
8+
9+
1. Check the inputs and outputs
10+
- INPUT: Optional[TreeNode]
11+
- OUTPUT: List[List[int]]
12+
13+
# Naive Solution
14+
15+
### Thought Process
16+
17+
1. BFS
18+
2. record the level, odds (from left to right) / evens (from right to left)
19+
- Implement
20+
21+
```python
22+
# Definition for a binary tree node.
23+
# class TreeNode:
24+
# def __init__(self, val=0, left=None, right=None):
25+
# self.val = val
26+
# self.left = left
27+
# self.right = right
28+
class Solution:
29+
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
30+
if not root:
31+
return []
32+
33+
# initial
34+
result = []
35+
q = collections.deque()
36+
level = 0
37+
38+
# put root into queue
39+
q.append(root)
40+
while q:
41+
lenq = len(q)
42+
level += 1
43+
r = collections.deque()
44+
for i in range(lenq):
45+
current = q.popleft()
46+
47+
if (level % 2) == 1:
48+
r.append(current.val)
49+
else:
50+
r.appendleft(current.val)
51+
52+
if current.left:
53+
q.append(current.left)
54+
if current.right:
55+
q.append(current.right)
56+
result.append(r)
57+
return result
58+
```

0 commit comments

Comments
 (0)