Python | Leetcode Python题解之第103题二叉树的锯齿形层序遍历

题目:

题解:

python 复制代码
class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root: return []
        res, deque = [], collections.deque()
        deque.append(root)
        while deque:
            tmp = []
            # 打印奇数层
            for _ in range(len(deque)):
                # 从左向右打印
                node = deque.popleft()
                tmp.append(node.val)
                # 先左后右加入下层节点
                if node.left: deque.append(node.left)
                if node.right: deque.append(node.right)
            res.append(tmp)
            if not deque: break # 若为空则提前跳出
            # 打印偶数层
            tmp = []
            for _ in range(len(deque)):
                # 从右向左打印
                node = deque.pop()
                tmp.append(node.val)
                # 先右后左加入下层节点
                if node.right: deque.appendleft(node.right)
                if node.left: deque.appendleft(node.left)
            res.append(tmp)
        return res
相关推荐
这里是小悦同学呀!1 小时前
python学习day2
java·python·学习
未来可期叶5 小时前
如何用Python批量解压ZIP文件?快速解决方案
python
张槊哲5 小时前
ROS2架构介绍
python·架构
风逸hhh6 小时前
python打卡day29@浙大疏锦行
开发语言·前端·python
浩皓素6 小时前
深入理解For循环及相关关键字原理:以Python和C语言为例
c语言·python
英英_6 小时前
详细介绍一下Python连接MySQL数据库的完整步骤
数据库·python·mysql
水花花花花花6 小时前
GloVe 模型讲解与实战
python·深度学习·conda·pip
C_VuI6 小时前
如何安装cuda版本的pytorch
人工智能·pytorch·python
Star abuse6 小时前
机器学习基础课程-6-课程实验
人工智能·python·机器学习
代码小将7 小时前
力扣992做题笔记
算法·leetcode