LeetCode 筆記 - 103. Binary Tree Zigzag Level Order Traversal

題目在此 103. Binary Tree Zigzag Level Order Traversal

給定一個 Binary Tree
搜集每一層的數值,每隔一層搜集順序就需要反過來

解題思維

可以用 Breadth-First Search 來解決問題
唯一需要注意的地方就是每隔一層就要把取得的結果反過來以符合他的題意

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:

if not root:
return []

upper_layer = [root]
lower_layer = []

result = []

level = 0
while upper_layer:
current_result = []
for node in upper_layer:
current_result.append(node.val)

if node.left:
lower_layer.append(node.left)
if node.right:
lower_layer.append(node.right)
level += 1
if level % 2 == 0:
current_result = reversed(current_result)

result.append(current_result)

upper_layer = lower_layer
lower_layer = []

return result

也許你也會想看看