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
相关推荐
蓝莓味柯基13 分钟前
Python3:文件操作
python
OpenC++27 分钟前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
xiaoh_71 小时前
解决视频处理中的 HEVC 解码错误:Could not find ref with POC xxx【已解决】
python·ffmpeg·音视频
明月与玄武1 小时前
Python编程的真谛:超越语法,理解编程本质
python·编程语言
CodeCraft Studio1 小时前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
এ᭄画画的北北2 小时前
力扣-160.相交链表
算法·leetcode·链表
拾忆-eleven2 小时前
C语言实战:用Pygame打造高难度水果消消乐游戏
c语言·python·pygame
旦莫2 小时前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
豌豆花下猫3 小时前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
小杨4043 小时前
python入门系列二十(peewee)
人工智能·python·pycharm