Approach
Breadth-first search
For Binary Tree Vertical Order Traversal, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 40 lines of Java from the credited upstream file 314.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<List<Integer>> verticalOrder(TreeNode root) {3 if (root == null)4 return new ArrayList<>();5 6 List<List<Integer>> ans = new ArrayList<>();7 Queue<Pair<TreeNode, Integer>> q = new ArrayDeque<>(); 8 int[] range = new int[2];9 getRange(root, range, 0); 10 11 for (int i = range[0]; i <= range[1]; ++i)12 ans.add(new ArrayList<>());13 14 q.offer(new Pair<>(root, -range[0]));15 16 while (!q.isEmpty()) {17 final TreeNode node = q.peek().getKey();18 final int x = q.poll().getValue();19 ans.get(x).add(node.val);20 if (node.left != null)21 q.offer(new Pair<>(node.left, x - 1));22 if (node.right != null)23 q.offer(new Pair<>(node.right, x + 1));24 }25 26 return ans;27 }28 29 private void getRange(TreeNode root, int[] range, int x) {30 if (root == null)31 return;32 33 range[0] = Math.min(range[0], x);34 range[1] = Math.max(range[1], x);35 36 getRange(root.left, range, x - 1);37 getRange(root.right, range, x + 1);38 }39}40