码迷,mamicode.com
首页 > 其他好文 > 详细

103. Binary Tree Zigzag Level Order Traversal

时间:2019-04-13 17:36:52      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:list   指示器   app   def   依次   treenode   bsp   区别   ...   

树的蜿蜒型层次遍历

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

和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

标签:list   指示器   app   def   依次   treenode   bsp   区别   ...   

原文地址:https://www.cnblogs.com/mangmangbiluo/p/10702007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!