程序媛詹妮弗
终身学习

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:

Input: [3,9,20,null,null,15,7]

   3
  /\
 /  \
 9  20
    /\
   /  \
  15   7 

Output:

[
  [9],
  [3,15],
  [20],
  [7]
]

思路

 

代码

 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         // corner
13         List<List<Integer>> results = new ArrayList<>();
14         if (root == null) return results;
15         // init
16         int min = Integer.MAX_VALUE;
17         int max = Integer.MIN_VALUE;
18         Map<Integer, List<Integer>> map = new HashMap<>();
19         Queue<Position> queue = new LinkedList<>();
20         
21         //use queue to bfs
22         queue.add(new Position(root, 0));
23         while (!queue.isEmpty()) {
24             Position position = queue.remove();
25             min = Math.min(min, position.column);
26             max = Math.max(max, position.column);
27             List<Integer> list = map.get(position.column);
28             if (list == null) {
29                 list = new ArrayList<>();
30                 map.put(position.column, list);
31             }
32             list.add(position.node.val);
33             if (position.node.left != null) queue.add(new Position(position.node.left, position.column-1));
34             if (position.node.right != null) queue.add(new Position(position.node.right, position.column+1));
35         }
36         for(int i = min; i<= max; i++) {
37             List<Integer> list = map.get(i);
38             if (list != null) results.add(list);
39         }
40         return results;
41     }
42 }
43 
44 class Position {
45     TreeNode node;
46     int column;
47     Position(TreeNode node, int column) {
48         this.node = node;
49         this.column = column;
50     }
51 }

 

posted on 2018-10-18 15:01  程序媛詹妮弗  阅读(107)  评论(0编辑  收藏  举报