題目出處
103. Binary Tree Zigzag Level Order Traversal
難度
medium
個人範例程式碼
# 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 []
ans = []
this_layer = [root]
reverse_flag = False
while this_layer:
this_layer_ans = []
next_layer = []
for node in this_layer:
this_layer_ans.append(node.val)
if node.left:
next_layer.append(node.left)
if node.right:
next_layer.append(node.right)
if reverse_flag:
this_layer_ans.reverse()
ans.append(this_layer_ans[:]) # deepcopy
this_layer = next_layer
reverse_flag = not reverse_flag
return ans
算法說明
類似 level order traversal 的邏輯,只不過在 zigzag 中我們要做的是間隔 layer 反轉輸出的結果。
至於要反轉的話,加一個反轉 flag 即可輕鬆完成
input handling
如果沒有 root,return []
Boundary conditions
透過 layer 一層一層循環,直到下一層 layer 無東西為止。
Reference
⭐ Leetcode 解題紀錄 ⭐ | 題型 | 資料結構 | Python Solution | C++ Solution | Note | |
---|---|---|---|---|---|---|
⭐BFS 相關題型 ⭐ | ||||||
104 | Maximum Depth of Binary Tree | BFS (分層) | Python | |||
94 | Binary Tree Inorder Traversal | BFS (分層) | Tree | Python | 內含 處理 Tree 樹問題的重點 | |
102 | Binary Tree Level Order Traversal | BFS (分層) | Tree | Python | ||
103 | Binary Tree Zigzag Level Order Traversal | BFS (分層) | Tree | Python | ||
107 | Binary Tree Level Order Traversal II | BFS (分層) | Tree | Python | ||
133 | Clone Graph | BFS (分層) | Graph | Python | Graph 的基本操作 #重要題型 | |
127 | Word Ladder | BFS (分層), DFS | Graph | Python | ||
[Lint] 127 | Topological Sorting | BFS (拓撲) | Python | 內有 indegree, outdegree 介紹 #重要題型 | ||
207 | Course Schedule | BFS (拓樸) | Graph | Python | ||
210 | Course Schedule II | BFS (拓樸) | Graph | Python | ||
[Lint] 892 | Alien Dictionary | BFS (拓樸) | Graph | Python | ||
[Lint] 431 | Connected Component in Undirected Graph | BFS (連通塊) | Graph | Python | 內含 BFS 模板 #重要題型 | |
1091 | Shortest Path in Binary Matrix | BFS (最短路徑) | Matrix | Python | ||
⭐ Binary Serach 相關題型 ⭐ | ||||||
33 |