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]
]
Solution1:BFS + Hashmap(or arraylist)
思路: bfs遍历,并将每col的结果存在hashmap中(实现1_a)
(实现1_b)也可能先得到col的range,存在arraylist中
Time Complexity: O(N) Space Complexity: O(N)
因为要保持顺序,所以BFS比较好
Solution1a Code:
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
// map to restore result, since we dont know the range
Map<Integer, ArrayList<Integer>> map = new HashMap<>();
Queue<TreeNode> queue_node = new LinkedList<TreeNode>();
Queue<Integer> queue_col = new LinkedList<>();
int range_min = 0;
int range_max = 0;
queue_node.offer(root);
queue_col.offer(0);
while (!queue_node.isEmpty()) {
TreeNode node = queue_node.poll();
int col = queue_col.poll();
if (!map.containsKey(col)) {
map.put(col, new ArrayList<Integer>());
}
map.get(col).add(node.val);
if (node.left != null) {
queue_node.offer(node.left);
queue_col.offer(col - 1);
range_min = Math.min(range_min, col - 1);
}
if (node.right != null) {
queue_node.offer(node.right);
queue_col.offer(col + 1);
range_max = Math.max(range_max, col + 1);
}
}
for (int i = range_min; i <= range_max; i++) {
res.add(map.get(i));
}
return res;
}
}
Solution1b Code:
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
int[] range = new int[] {0, 0};
getRange(root, range, 0);
for (int i = range[0]; i <= range[1]; i++) {
res.add(new ArrayList<Integer>());
}
Queue<TreeNode> queue_node = new LinkedList<TreeNode>();
Queue<Integer> queue_col = new LinkedList<>();
queue_node.offer(root);
queue_col.offer(-range[0]);
while (!queue_node.isEmpty()) {
TreeNode node = queue_node.poll();
int col = queue_col.poll();
res.get(col).add(node.val);
if (node.left != null) {
queue_node.offer(node.left);
queue_col.offer(col - 1);
}
if (node.right != null) {
queue_node.offer(node.right);
queue_col.offer(col + 1);
}
}
return res;
}
private void getRange(TreeNode root, int[] range, int col) {
if (root == null) {
return;
}
range[0] = Math.min(range[0], col);
range[1] = Math.max(range[1], col);
getRange(root.left, range, col - 1);
getRange(root.right, range, col + 1);
}
}