LeetCode 314. Binary Tree Vertical Order Traversal

原题链接在这里:https://leetcode.com/problems/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:
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]
]

 Given binary tree [3,9,20,4,5,2,7],

    _3_
   /   \
  9    20
 / \   / \
4   5 2   7

return its vertical order traversal as:

[
  [4],
  [9],
  [3,5,2],
  [20],
  [7]
]

题解:

Binary Tree Level Order Traversal类似。

BFS, 把TreeNode和它所在的col分别放到两个queue中. dequeue后放TreeNode到对应的 colunm bucket里.

Example of [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]. Notice that every child access changes one column bucket id. So 12 actually goes ahead of 11.

Time Complexity: O(n). Space: O(n).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> verticalOrder(TreeNode root) {
12         List<List<Integer>> res = new ArrayList<List<Integer>>();
13         if(root == null){
14             return res;
15         }
16         HashMap<Integer, List<Integer>> colBucket = new HashMap<Integer, List<Integer>>();
17         LinkedList<TreeNode> que = new LinkedList<TreeNode>();
18         LinkedList<Integer> cols = new LinkedList<Integer>();
19         int min = 0;
20         int max = 0;
21         
22         que.add(root);
23         cols.add(0);
24         while(!que.isEmpty()){
25             TreeNode tn = que.poll();
26             int col = cols.poll();
27             if(!colBucket.containsKey(col)){
28                 colBucket.put(col, new ArrayList<Integer>());
29             }
30             colBucket.get(col).add(tn.val);
31             min = Math.min(min, col);
32             max = Math.max(max, col);
33             
34             if(tn.left != null){
35                 que.add(tn.left);
36                 cols.add(col-1);
37             }
38             if(tn.right != null){
39                 que.add(tn.right);
40                 cols.add(col+1);
41             }
42         }
43         for(int i = min; i<=max; i++){
44             res.add(colBucket.get(i));
45         }
46         return res;
47     }
48 }

便于理解,可以吧TreeNode和它对应的column number放在一个Pair里.

Time Complexity: O(n). Space: O(n).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public List<List<Integer>> verticalOrder(TreeNode root) {
18         List<List<Integer>> res = new ArrayList<>();
19         if(root == null){
20             return res;
21         }
22         
23         Map<Integer, List<Integer>> map = new HashMap<>();
24         int min = 0;
25         int max = 0;
26         LinkedList<Pair<Integer, TreeNode>> que = new LinkedList<>();
27         que.add(new Pair(0, root));
28         while(!que.isEmpty()){
29             Pair<Integer, TreeNode> cur = que.poll();
30             int col = cur.getKey();
31             TreeNode curNode = cur.getValue();
32             min = Math.min(min, col);
33             max = Math.max(max, col);
34             map.putIfAbsent(col, new ArrayList<Integer>());
35             map.get(col).add(curNode.val);
36             
37             if(curNode.left != null){
38                 que.add(new Pair(col - 1, curNode.left));
39             }
40             
41             if(curNode.right != null){
42                 que.add(new Pair(col + 1, curNode.right));
43             }
44         }
45         
46         for(int i = min; i <= max; i++){
47             res.add(map.get(i));
48         }
49         
50         return res;
51     }
52 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<vector<int>> verticalOrder(TreeNode* root) {
15         vector<vector<int>> res;
16         if(!root){
17             return res;
18         }
19 
20         unordered_map<int, vector<int>> map;
21         queue<pair<int, TreeNode*>> que;
22         que.push({0, root});
23         int minCol = 0;
24         int maxCol = 0;
25 
26         while(!que.empty()){
27             auto[col, curNode] = que.front();
28             que.pop();
29             minCol = min(minCol, col);
30             maxCol = max(maxCol, col);
31             map[col].push_back(curNode->val);
32 
33             if(curNode->left){
34                 que.push({col - 1, curNode->left});
35             }
36 
37             if(curNode->right){
38                 que.push({col + 1, curNode->right});
39             }
40         }
41 
42         for(int i = minCol; i <= maxCol; i++){
43             res.push_back(map[i]);
44         }
45 
46         return res;
47     }
48 };

AC Python:

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, val=0, left=None, right=None):
 4 #         self.val = val
 5 #         self.left = left
 6 #         self.right = right
 7 class Solution:
 8     def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
 9         if not root:
10             return []
11 
12         colMap = defaultdict(list)
13         que = deque([(0, root)])
14         minCol = maxCol = 0
15 
16         while que:
17             col, node = que.popleft()
18             minCol = min(minCol, col)
19             maxCol = max(maxCol, col)
20             colMap[col].append(node.val)
21             if node.left:
22                 que.append((col - 1, node.left))
23 
24             if node.right:
25                 que.append((col + 1, node.right))
26 
27         return [colMap[i] for i in range(minCol, maxCol + 1)]
28         

类似Vertical Order Traversal of a Binary Tree.

posted @ 2016-03-30 01:37  Dylan_Java_NYC  阅读(716)  评论(0编辑  收藏  举报