leetcode 103. Zigzag sequence traversal BFS method of binary tree

Question 102 is the "leading question" of this question, and the expression in the answer to question 102 will not be repeated here
https://blog.csdn.net/weixin_50791900/article/details/111569831
On the basis of question 102, only the reverse order traversal needs to be considered layer
here I use a variable level of the recording layer of the need to reverse traversal
is initially set to 0, each traversing one plus one (also a record depth of a binary tree)
odd layer requires reverse
the original order of traversal without changing
needs only in reverse convenience Insert the value at the head of the list in the layer.
Here I use the insert method to insert at the 0 bit to achieve the effect of reverse insertion.

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return[]

        ans = []
        a = collections.deque()
        a.append(root)
        level = 0

        while a:
            n = len(a)
            b = []

            for i in range(n):
                node = a.popleft()
                if level % 2 == 0:
                    b.append(node.val)
                if level % 2 != 0:
                    b.insert(0, node.val)
                if node.left:
                    a.append(node.left)
                if node.right:
                    a.append(node.right) 

            level += 1
            ans.append(b)
        return ans

The effect is acceptable

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/111570973