【Search (BFS)】Jianzhi Offer 32 - II. Print binary tree from top to bottom II

Title description :
Print a binary tree layer by layer from top to bottom. Nodes in the same layer are printed in order from left to right, and each layer is printed in one line.

Example :
insert image description here
Problem solution : how to determine which layer the current node is at, use the for loop, because in each while loop, the length of the current queue is always the length of the current layer, so use the for loop to add the result to the temporary The list is fine, so that the elements stored in the temporary list each time are just all the nodes of each layer.

# 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]]:
        #如何去分辨当前节点在哪一层,加入一个for循环
        from collections import deque
        queue = deque()
        queue.append(root)
        if not root:
            return []
        tmp = []
        result = []
        while queue:
            for i in range(len(queue)):
                node = queue.popleft()
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            result.append(tmp)
            tmp = []
        return result

Guess you like

Origin blog.csdn.net/Rolandxxx/article/details/128986478