【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III

简介: 本文介绍了两种Python实现方法,用于按照之字形顺序打印二叉树的层次遍历结果,实现了在奇数层正序、偶数层反序打印节点的功能。

1 题目

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[ [3],[20,9],[15,7]]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2 解析

思路和【剑指 Offer 32 - II. 从上到下打印二叉树 II】一样,区别在此基础上,只改进一点,奇数层列表是正序,偶数层列表是反序。

3 python实现

(1)写法一

    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        from collections import deque
        res,queue = [],deque()
        queue.append(root)    
        count = 1 
        while queue:
            level_list = []
            for _ in range(len(queue)):

                node = queue.popleft()
                level_list.append(node.val)
                if node.left:queue.append(node.left)
                if node.right:queue.append(node.right)
            if count%2==0:
                res.append(level_list[::-1])
            else:
                res.append(level_list)
            count+=1
        return res

(2)写法二,用列表来替代双相队列dqueue

def levelOrder(self, root: TreeNode) -> List[List[int]]:
    if not root: return []
    res,queue = [],[root,]  
    count = 1 
    while queue:
        level_list = []
        for _ in range(len(queue)):
            node = queue.pop(0)
            level_list.append(node.val)
            if node.left:queue.append(node.left)
            if node.right:queue.append(node.right)
            if count%2==0:
                res.append(level_list[::-1])
            else:
                res.append(level_list)
                count+=1
                return res
目录
相关文章
|
9天前
|
搜索推荐 Python
Leecode 101刷题笔记之第五章:和你一起你轻松刷题(Python)
这篇文章是关于LeetCode第101章的刷题笔记,涵盖了多种排序算法的Python实现和两个中等难度的编程练习题的解法。
15 3
|
12天前
【LeetCode 31】104.二叉树的最大深度
【LeetCode 31】104.二叉树的最大深度
12 2
|
12天前
【LeetCode 29】226.反转二叉树
【LeetCode 29】226.反转二叉树
12 2
|
12天前
【LeetCode 28】102.二叉树的层序遍历
【LeetCode 28】102.二叉树的层序遍历
10 2
|
9天前
|
算法 C++ Python
Leecode 101刷题笔记之第四章:和你一起你轻松刷题(Python)
这篇博客是关于LeetCode上使用Python语言解决二分查找问题的刷题笔记,涵盖了从基础到进阶难度的多个题目及其解法。
11 0
|
9天前
|
算法 C++ Python
Leecode 101刷题笔记之第三章:和你一起你轻松刷题(Python)
本文是关于LeetCode算法题的刷题笔记,主要介绍了使用双指针技术解决的一系列算法问题,包括Two Sum II、Merge Sorted Array、Linked List Cycle II等,并提供了详细的题解和Python代码实现。
11 0
|
9天前
|
算法 C++ 索引
Leecode 101刷题笔记之第二章:和你一起你轻松刷题(Python)
本文是关于LeetCode 101刷题笔记的第二章,主要介绍了使用Python解决贪心算法题目的方法和实例。
7 0
|
12天前
【LeetCode 43】236.二叉树的最近公共祖先
【LeetCode 43】236.二叉树的最近公共祖先
10 0
|
12天前
【LeetCode 38】617.合并二叉树
【LeetCode 38】617.合并二叉树
8 0
|
12天前
【LeetCode 37】106.从中序与后序遍历构造二叉树
【LeetCode 37】106.从中序与后序遍历构造二叉树
9 0