Approach
Depth-first search
For Vertical Order Traversal of a Binary Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 29 lines of Java from the credited upstream file 987.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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>> verticalTraversal(TreeNode root) {3 List<List<Integer>> ans = new ArrayList<>();4 TreeMap<Integer, List<int[]>> xToSortedPairs = new TreeMap<>(); 5 6 dfs(root, 0, 0, xToSortedPairs);7 8 for (List<int[]> pairs : xToSortedPairs.values()) {9 Collections.sort(pairs, Comparator.comparingInt((int[] pair) -> pair[0])10 .thenComparingInt((int[] pair) -> pair[1]));11 List<Integer> vals = new ArrayList<>();12 for (int[] pair : pairs)13 vals.add(pair[1]);14 ans.add(vals);15 }16 17 return ans;18 }19 20 private void dfs(TreeNode root, int x, int y, TreeMap<Integer, List<int[]>> xToSortedPairs) {21 if (root == null)22 return;23 xToSortedPairs.putIfAbsent(x, new ArrayList<>());24 xToSortedPairs.get(x).add(new int[] {y, root.val});25 dfs(root.left, x - 1, y + 1, xToSortedPairs);26 dfs(root.right, x + 1, y + 1, xToSortedPairs);27 }28}29