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

[LC] 103. Binary Tree Zigzag Level Order Traversal

时间:2019-10-22 12:51:51      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:turn   nod   ini   append   sel   treenode   bsp   imp   span   

Given a binary tree, return the zigzag level order traversal of its nodes‘ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   /   9  20
    /     15   7

 

return its zigzag level order traversal as:

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

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

class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        from collections import deque
        res = []
        if root is None:
            return res
        is_even = False
        my_deque = deque()
        my_deque.append(root)
        while my_deque:
            size = len(my_deque)
            lst = []
            for _ in range(size):
                if is_even:
                    cur = my_deque.pop()
                    if cur.right:
                        my_deque.appendleft(cur.right)
                    if cur.left:
                        my_deque.appendleft(cur.left)
                else:
                    cur = my_deque.popleft()
                    if cur.left:
                        my_deque.append(cur.left)
                    if cur.right:
                        my_deque.append(cur.right)
                lst.append(cur.val)
            res.append(lst)
            is_even = not is_even
        return res

 

[LC] 103. Binary Tree Zigzag Level Order Traversal

标签:turn   nod   ini   append   sel   treenode   bsp   imp   span   

原文地址:https://www.cnblogs.com/xuanlu/p/11718930.html

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