leetcode 103. 二叉树的锯齿形层序遍历 BFS方法

102题为本题的“先导题”,102题解答中的表述本题解答不再赘述
https://blog.csdn.net/weixin_50791900/article/details/111569831
在102题的基础上,仅需考虑逆序遍历的层
在此我运用了level变量记录该层是否需要倒序遍历
初始设为0,每遍历一层加一(同样是记录二叉树的深度)
奇数层需要逆序
原来的遍历顺序无需改变
仅需要在逆序便利的层中将值在列表头插入
在这里我运用的insert方法在0位插入实现的逆序插入的效果

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

效果尚可

猜你喜欢

转载自blog.csdn.net/weixin_50791900/article/details/111570973