Leetcode 103. Binary Tree Zigzag Level Order Traversal

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]
]


思路类似: level order Traversal,唯一的区别在于对于某些层,最后需要reverse以下,再push进ans

 1 class Solution(object):
 2     def zigzagLevelOrder(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[List[int]]
 6         """
 7         ans = []
 8         if not root:
 9             return ans
10         queue = [root]
11         direct = True
12         while queue:
13             line = []
14             size = len(queue)
15             for i in range(size):
16                 cur = queue.pop(0)
17                 line.append(cur.val)
18                 if cur.right:
19                     queue.append(cur.right)
20                 if cur.left:
21                     queue.append(cur.left)
22             
23             if direct == True:
24                 ans.append(line[::-1])
25             else:
26                 ans.append(line)
27             
28             direct = not direct
29         
30         return ans

 

posted @ 2017-01-25 00:53  lettuan  阅读(130)  评论(0编辑  收藏  举报