示例1:
輸入:root = [3,9,20,null,null,15,7]
輸出:[[3],[9,20],[15,7]
示例2:
輸入:root = [1]
輸出:[[1]
示例3:
輸入:root = []
輸出: []
Example 1: Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Example 2: Input: root = [1] Output: [[1]] Example 3: Input: root = [] Output: []Q = Deque([[root]) latve = [[root.val]] temp = deque() 而問: 節點= q.popleft() if node.left:temp.append(node.left) 如果node.right:temp.append(node.right) 如果不是Q: 如果溫度: levels.append([n. val for n in temp中]) Q =溫度 temp = deque() 返回水平
class Solution(object): def levelOrder(self, root): if not root: return [] Q = deque([root]) levels = [[root.val]] temp = deque() while Q: node = Q.popleft() if node.left: temp.append(node.left) if node.right: temp.append(node.right) if not Q: if temp: levels.append([n.val for n in temp]) Q = temp temp = deque() return levels在所有提供的實現中使用的編碼模式是
這種模式通常按級別遍歷樹的水平,在移至下一個深度之前,在當前深度處處理所有節點。
BFS是使用隊列數據結構實現的,以跟踪每個級別的節點。
該解決方案的時間和空間複雜性
時間複雜度為o(n),因為每個節點一次訪問一次。
廣度優先搜索
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3