Hint: Label columns from root 0, left -1, right +1, then read left to right [OK]
Common Mistakes:
Ignoring multiple nodes in same column order
Mixing preorder or inorder output with vertical order
Not assigning correct column indices
4. Given this Java snippet for vertical order traversal, what is the error?
Map map = new HashMap<>();
Queue> queue = new LinkedList<>();
queue.add(new Pair(root, 0));
while (!queue.isEmpty()) {
Pair p = queue.poll();
TreeNode node = p.getKey();
int col = p.getValue();
map.putIfAbsent(col, new ArrayList<>());
map.get(col).add(node.val);
if (node.left != null) queue.add(new Pair(node.left, col - 1));
if (node.right != null) queue.add(new Pair(node.right, col + 1));
}
medium
A. Pair class is not imported or defined
B. Queue should be a Stack for correct traversal
C. map.putIfAbsent should be replaced with map.put
D. col should be incremented for left child, not decremented
Solution
Step 1: Check usage of Pair class
The code uses Pair but Java does not have Pair by default; it must be imported or defined.
Step 2: Identify missing import or definition
Without importing javafx.util.Pair or defining a custom Pair class, this code will not compile.
Final Answer:
Pair class is not imported or defined -> Option A
Quick Check:
Missing Pair class causes compile error [OK]
Hint: Check if all classes like Pair are imported or defined [OK]
Common Mistakes:
Assuming Pair is built-in in Java standard library
Using Stack instead of Queue for BFS traversal
Incorrect column increment direction for left child
5. How would you modify vertical order traversal to output nodes sorted by row and then value within each vertical column?
Choose the best approach.
hard
A. Use a Queue and print nodes as they are visited
B. Use a HashMap and sort each list after traversal
C. Use a Stack to store nodes and pop in sorted order
D. Use a TreeMap> to map column -> row -> sorted nodes
Solution
Step 1: Understand sorting by row and value in vertical columns
We need to group nodes by column, then by row, and sort nodes with same row by value.
Step 2: Choose data structure supporting nested sorting
TreeMap for columns and rows keeps keys sorted. PriorityQueue stores nodes sorted by value. So TreeMap> fits.
Final Answer:
Use a TreeMap> to map column -> row -> sorted nodes -> Option D
Quick Check:
Nested TreeMaps + PriorityQueue = sorted vertical order [OK]
Hint: Use nested TreeMaps and PriorityQueue for sorted vertical order [OK]
Common Mistakes:
Sorting lists after traversal loses row info
Using Stack or Queue which don't sort nodes
Ignoring row sorting within columns
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.