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,8,4,0,1,7],
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
return its vertical order traversal as:
[
[4],
[9],
[3,0,1],
[8],
[7]
]
Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
3
/\
/ \
9 8
/\ /\
/ \/ \
4 01 7
/\
/ \
5 2
return its vertical order traversal as:
[
[4],
[9,5],
[3,0,1],
[8,2],
[7]
]
Tips:
BFS,需要两个queue和一个HashMap。min和max存最小和最大的列数。两个queue同时FIFO,分别存这个node的值和他的col。
The following solution takes 5ms.
BFS, put node, col into queue at the same time Every left child access col - 1 while right child col + 1 This maps node into different col buckets Get col boundary min and max on the fly Retrieve result from cols Note that TreeMap version takes 9ms.
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> cols = new LinkedList<>();
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
queue.offer(root);
cols.offer(0);
int min = 0;
int max = 0;
while (!queue.isEmpty()) {
TreeNode curt = queue.poll();
int col = cols.poll();
if (!map.containsKey(col)) {
map.put(col, new ArrayList<Integer>());
}
map.get(col).add(curt.val);
if (curt.left != null) {
cols.offer(col - 1);
queue.offer(curt.left);
min = Math.min(min, col - 1);
}
if (curt.right != null) {
cols.offer(col + 1);
queue.offer(curt.right);
max = Math.max(max, col + 1);
}
}
for (int i = min; i <= max; i++) {
result.add(map.get(i));
}
return result;
}
}
TreeMap Version:
public int index = 0;
public TreeMap<Integer, List<Integer>> tm;
public class Pair {
TreeNode node;
int index;
public Pair(TreeNode n, int i) {
node = n;
index = i;
}
}
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
tm = new TreeMap<Integer, List<Integer>>();
if (root == null) return res;
Queue<Pair> q = new LinkedList<Pair>();
q.offer(new Pair(root, 0));
while (!q.isEmpty()) {
Pair cur = q.poll();
if (!tm.containsKey(cur.index)) tm.put(cur.index, new ArrayList<Integer>());
tm.get(cur.index).add(cur.node.val);
if (cur.node.left != null) q.offer(new Pair(cur.node.left, cur.index-1));
if (cur.node.right != null) q.offer(new Pair(cur.node.right, cur.index+1));
}
for (int key : tm.keySet()) res.add(tm.get(key));
return res;
}