Vertical Order Traversal of a Binary Tree - Problem

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

Input & Output

Example 1 — Basic Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
💡 Note: Column -1: node 9 at (1,-1). Column 0: node 3 at (0,0), node 15 at (2,0). Column 1: node 20 at (1,1). Column 2: node 7 at (2,2). Sorted by column from left to right.
Example 2 — Same Position Nodes
$ Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
💡 Note: Column -2: node 4. Column -1: node 2. Column 0: nodes 1,5,6 sorted by row then value. Column 1: node 3. Column 2: node 7.
Example 3 — Single Node
$ Input: root = [1]
Output: [[1]]
💡 Note: Single node at position (0,0), so only one column with one element.

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • 0 ≤ Node.val ≤ 1000

Visualization

Tap to expand
INPUT TREEALGORITHM STEPSFINAL RESULT3(0,0)9(1,-1)20(1,1)15(2,0)7(2,2)Binary tree withcoordinate systemRow: depth levelCol: left=-1, right=+11DFS TraversalVisit nodes systematically2Group by ColumnAdd nodes to column map3Sort Within ColumnsBy row, then by value4Combine ColumnsLeft to right orderColumn Map:Col -1: [9]Col 0: [3,15] Col 1: [20] Col 2: [7]Vertical Order ResultColumn -1: [9]Column 0: [3, 15]Column 1: [20]Column 2: [7][[9],[3,15],[20],[7]]Each column contains nodessorted top-to-bottom,then by valueTime: O(n log n)Space: O(n)Key Insight:Assign coordinates to each node: left child at (row+1, col-1), right child at (row+1, col+1).Group nodes by column, sort within each column by row then value, then combine columns left-to-right.TutorialsPoint - Vertical Order Traversal of Binary Tree | DFS with Column Map
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
89.0K Views
High Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen