LeetCode | 面試題32 - II. 從上到下打印二叉樹 II【劍指Offer】【Python】

LeetCode 面試題32 - II. 從上到下打印二叉樹 II【劍指Offer】【Easy】【Python】【二叉樹】【BFS】

問題

力扣

從上到下按層打印二叉樹,同一層的節點按從左到右的順序打印,每一層打印到一行。

例如:
給定二叉樹: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其層次遍歷結果:

[
  [3],
  [9,20],
  [15,7]
]

提示:

  1. 節點總數 <= 1000

注意:本題與主站 102 題 相同

思路

BFS

當隊列不爲空:
	當前層打印循環:
		隊首元素出隊,記爲 node
		將 node.val 添加到 temp 尾部
		若左(右)子節點不爲空,則將左(右)子節點加入隊列
	把當前 temp 中的所有元素加入 res

時間複雜度: O(n),n 爲二叉樹的節點數。
空間複雜度: O(n),n 爲二叉樹的節點數。

Python3代碼
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        import collections
        if not root:
            return []
        
        res, q = [], collections.deque()
        q.append(root)
        while q:
            # 輸出是二維數組
            temp = []
            for x in range(len(q)):
                node = q.popleft()
                temp.append(node.val)
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            res.append(temp)
        return res

GitHub鏈接

Python

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章