0314. Binary Tree Vertical Order Traversal
Last updated
Last updated
**Input:** root = [3,9,20,null,null,15,7]
**Output:** [[9],[3,15],[20],[7]]**Input:** root = [3,9,8,4,0,1,7]
**Output:** [[4],[9],[3,0,1],[8],[7]]**Input:** root = [3,9,8,4,0,1,7,null,null,null,2,5]
**Output:** [[4],[9,5],[3,0,1],[8,2],[7]]**Input:** root = []
**Output:** []/**
* 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<List<Integer>>();
// edge case
if (root == null) return res;
TreeMap<Integer, List<Integer>> tm = new TreeMap<>();
// BFS
Queue<TreeNode> q = new LinkedList<>();
tm.put(0, new ArrayList<Integer>());
tm.get(0).add(root.val);
root.val = 0;
q.offer(root);
while (!q.isEmpty()) {
TreeNode curr = q.poll();
// left
if (curr.left != null) {
if (!tm.containsKey(curr.val-1)) tm.put(curr.val-1, new ArrayList<Integer>());
tm.get(curr.val-1).add(curr.left.val);
curr.left.val = curr.val-1;
q.offer(curr.left);
}
// right
if (curr.right != null) {
if (!tm.containsKey(curr.val+1)) tm.put(curr.val+1, new ArrayList<Integer>());
tm.get(curr.val+1).add(curr.right.val);
curr.right.val = curr.val+1;
q.offer(curr.right);
}
}
for (int i : tm.keySet()) {
res.add(tm.get(i));
}
return res;
}
} 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 /\ / \ 5 2 [ [4], [9,5], [3,0,1], [8,2], [7] ]