103. Binary Tree Zigzag Level Order Traversal

Posted mangmangbiluo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了103. Binary Tree Zigzag Level Order Traversal相关的知识,希望对你有一定的参考价值。

树的蜿蜒型层次遍历

要求第一层从左向右,第二层从右向左...依次类推

和102题无本质区别,加一个翻转指示器即可

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

class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        nodelist = [root]
        result = []
        order = True
        while nodelist:
            tmplist = []
            vallist = []
            for node in nodelist:
                vallist.append(node.val)
                if node.left:
                    tmplist.append(node.left)
                if node.right:
                    tmplist.append(node.right)
            if not order:
                vallist.reverse()
            order = not order
            result.append(vallist)
            nodelist = tmplist
        return result

 

以上是关于103. Binary Tree Zigzag Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal

LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告

[leetcode tree]103. Binary Tree Zigzag Level Order Traversal

[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal

103. Binary Tree Zigzag Level Order Traversal