首页 > 其他 > 详细

Leetcode 314. Binary Tree Vertical Order Traversal

时间:2017-05-14 09:47:39      阅读:292      评论:0      收藏:0      [点我收藏+]

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                 

 

Leetcode 314. Binary Tree Vertical Order Traversal

原文:http://www.cnblogs.com/lettuan/p/6851602.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!