Leetcode 314. Binary Tree Vertical Order Traversal

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:

 

  1. Given binary tree [3,9,20,null,null,15,7],
       3
      /\
     /  \
     9  20
        /\
       /  \
      15   7
    

     

    return its vertical order traversal as:

    [
      [9],
      [3,15],
      [20],
      [7]
    ]
    
  2. Given binary tree [3,9,8,4,0,1,7],
         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7
    

     

    return its vertical order traversal as:

    [
      [4],
      [9],
      [3,0,1],
      [8],
      [7]
    ]

 

这一题最重要的就是使用defaultdict(list), 这样可以把(feature, id)按照feature分类group起来。再就是如果queue里面是tuple ( i.e. (a,b) ),必须import Queue。有一点不明白的是L11, 如果把tuple写成(0, root)就会报错。

 

 1 class Solution(object):
 2     def verticalOrder(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[List[int]]
 6         """
 7         results = collections.defaultdict(list)
 8         
 9         import Queue
10         que = Queue.Queue()
11         que.put((root, 0))
12         
13         while not que.empty():
14             node, level = que.get()
15             if node:
16                 results[level].append(node.val)
17                 que.put((node.left, level - 1))
18                 que.put((node.right, level + 1))
19         
20         return [results[level] for level in sorted(results)]
21                 

 

posted @ 2017-05-14 09:10  lettuan  阅读(217)  评论(0编辑  收藏  举报