力扣刷题笔记:剑指 Offer 32 - III. 从上到下打印二叉树 III(单纯的列表、队列queue,对二叉树进行逐层遍历,再将每层按奇偶分顺逆序)

题目:

剑指 Offer 32 - III、从上到下打印二叉树 III

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

例如:
给定二叉树: [3,9,20,null,null,15,7],
在这里插入图片描述

返回其层次遍历结果:

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

提示:

节点总数 <= 1000

题解思路:

单纯利用列表对二叉树进行逐层遍历,再将每层按奇偶分顺逆序。

题解python代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root: return []
        ans, queue = [], collections.deque()
        queue.append(root) #初始化queue为root
        while queue:
            temp = []  #定义层输出列表
            for _ in range(len(queue)):
                node = queue.popleft()  #取出queue最左的元素,并在queue添加左右子树
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
                temp.append(node.val)  #层输出列表添加node的值
            ans.append(temp[::-1] if len(ans)%2!=0 else temp)  #按照ans的长度的奇偶情况,判断是否需要逆序
        return ans

在这里插入图片描述

作者:a-qing-ge
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/solution/dan-chun-li-yong-lie-biao-dui-er-cha-shu-gjgu/
来源:力扣(LeetCode)https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

猜你喜欢

转载自blog.csdn.net/weixin_44414948/article/details/113783424