/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<>();
HashMap<TreeNode, Integer> weight = new HashMap<>();
queue.offer(root);
weight.put(root, 0);
int min = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int w = weight.get(node);
if (!map.containsKey(w)) {
map.put(w, new ArrayList<Integer>());
}
map.get(w).add(node.val);
if (node.left != null) {
queue.add(node.left);
weight.put(node.left, w - 1);
}
if (node.right != null) {
queue.add(node.right);
weight.put(node.right, w + 1);
}
min = Math.min(min, w);
}
while (map.containsKey(min)) {
res.add(map.get(min++));
}
return res;
}
}
Here we use HashMap to store <absolute col number, corresponding elements in that level>, weight to store relative col for elements.
The following solution is basically the same, but it used a Queue to store the column values:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> cols = new LinkedList<>();
queue.offer(root);
cols.add(0);
int min = 0;
int max = 0;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
int col = cols.poll();
if (!map.containsKey(col)) {
map.put(col, new ArrayList<Integer>());
}
map.get(col).add(node.val);
if (node.left != null) {
queue.add(node.left);
cols.add(col - 1);
min = Math.min(min, col - 1);
}
if (node.right != null) {
queue.add(node.right);
cols.add(col + 1);
max = Math.max(max, col + 1);
}
}
for (int i = min; i <= max; i++) {
res.add(map.get(i));
}
return res;
}
}
HashMap solution:
Here we use HashMap to store <absolute col number, corresponding elements in that level>, weight to store relative col for elements.
The following solution is basically the same, but it used a Queue to store the column values: