Likou 102. Order Traversal of Binary Trees

The source of the topic: 102. The level-order traversal of the binary tree
topic: give you the root node root of the binary tree, and return the level-order traversal of its node value. (i.e. layer by layer, visiting all nodes from left to right).
insert image description here
insert image description here
Idea: Binary tree traversal includes depth-first traversal (DBS) and breadth-first traversal (BFS). Depth-first traversal includes pre-order traversal, in-order traversal, and subsequent traversal. Breadth-first traversal is level-order traversal. Layer order traversal is inseparable from the queue. Using the idea of ​​FIFO and LIFO, first put the head node of the binary tree into the queue, then pop the head node, and then put the left and right children of the head node. Join the queue, store the head node in the queue, then pop the left child, then add the left and right children of the left child to the queue in turn, then add the value of the left child to the queue, and then pop the right child. , then the left and right children of the right child are added to the queue in turn, so that the left and right children of the right child follow the left and right children of the left child in sequence, and then the left and right children of the left child and the left and right children of the right child will pop up in sequence according to the characteristics of the queue. Children, loop continuously until there is no node in the queue and it is empty, that is, all nodes are stored in the queue in turn and returned.
The specific code is as follows:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        list1 = []
        queue = [root]
        while queue:
            list2 = []
            for i in range(len(queue)):
                a = queue.pop(0)
                if a.left:
                    queue.append(a.left)
                if a.right:
                    queue.append(a.right)
                list2.append(a.val)
            list1.append(list2)
        return list1

insert image description here

Reference link: leetcode-level order traversal of
binary tree python implementation 102. level order traversal of binary tree (python)
b station explanation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339862&siteId=291194637