Leetcode 314. Binary Tree Vertical Order Traversal

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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                 

 



以上是关于Leetcode 314. Binary Tree Vertical Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 314. Binary Tree Vertical Order Traversal

[LeetCode] 314. Binary Tree Vertical Order Traversal

LeetCode 314. Binary Tree Vertical Order Traversal(二叉树垂直遍历)

314. Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal