LeetCode |. Face questions 32 - II are printed upside down to prove safety Offer binary II [] [Python]

LeetCode interview questions 32 -. II printed upside down binary wins the Offer [II] [Easy binary] [] [] [Python] BFS

problem

Power button

Printing the binary tree in layers from top to bottom, from left to right to print the same layer nodes, each layer printed on one line.

For example:
Given a binary tree: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

Return to its level through the results:

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

prompt:

  1. 节点总数 <= 1000

NOTE: The main problem with the station 102 issues the same

Thinking

BFS

当队列不为空:
    当前层打印循环:
        队首元素出队,记为 node
        将 node.val 添加到 temp 尾部
        若左(右)子节点不为空,则将左(右)子节点加入队列
    把当前 temp 中的所有元素加入 res

Time complexity: O (n-), n-number of nodes of the binary tree.
Space complexity: O (n-), n-number of nodes of the binary tree.

Python3 Code
# 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 link

Python

Guess you like

Origin www.cnblogs.com/wonz/p/12535587.html