class TreeNode { public int val; public TreeNode left, right; public TreeNode(int x) { val = x; } } // Tree structure: // 1 // / \ // 2 3 // / \ // 4 5 // Vertical order traversal groups nodes by their vertical columns. // Expected output format: [[4], [2], [1], [3], [5]] // Code to perform vertical order traversal is assumed correct and omitted for brevity.
Vertical order traversal groups nodes by their horizontal distance from the root. Nodes to the left have negative distance, root is zero, right is positive.
Here, 4 is farthest left, then 2, then 1, then 3, then 5.
Horizontal distance is how far left or right a node is from the root horizontally.
Root is 0, left child decreases by 1, right child increases by 1.
class TreeNode { public int val; public TreeNode left, right; public TreeNode(int x) { val = x; } } // Vertical order traversal groups nodes by horizontal distance. // Nodes in the same column are listed top to bottom. // Code to perform traversal is assumed correct and omitted.
Nodes with horizontal distance -1: 2, then 6 (top to bottom)
Distance 0: 1, then 4 (top to bottom)
Distance 1: 3
Distance 2: 5
Distance 3: 7
The dictionary 'map' does not initialize a list for a new horizontal distance key before adding values.
Accessing map[hd] when hd is not a key causes KeyNotFoundException.
Horizontal distances:
- 10: 0
- 7: -1
- 15: 1
- 5: -2
- 8: 0
- 20: 2
- 3: -3
- 25: 3
Unique distances: -3, -2, -1, 0, 1, 2, 3 → 7 columns
But 8 shares 0 with 10, so total unique columns are 7.
