Vertical Order Traversal of a Binary Tree - Problem
Vertical Order Traversal of a Binary Tree

Imagine viewing a binary tree from above and projecting all nodes onto a 2D grid. Each node occupies a position (row, col) where the root starts at (0, 0). When you move to a left child, you go one row down and one column left: (row + 1, col - 1). For a right child, you go one row down and one column right: (row + 1, col + 1).

Your task is to return the vertical order traversal - a list of node values grouped by column, ordered from leftmost to rightmost column. Within each column, nodes should be ordered from top to bottom by row. If multiple nodes share the same (row, col) position, sort them by their values in ascending order.

Goal: Return a 2D list where each inner list contains all node values in a specific column, ordered correctly.

Input: Root of a binary tree
Output: List of lists representing vertical order traversal

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [3,9,20,null,null,15,7]
โ€บ Output: [[9],[3,15],[20],[7]]
๐Ÿ’ก Note: Root at (0,0), left child 9 at (-1,1), right child 20 at (1,1). Node 20 has children 15 at (0,2) and 7 at (2,2). Column -1: [9], Column 0: [3,15] (3 comes before 15 by row), Column 1: [20], Column 2: [7].
example_2.py โ€” Same Position Nodes
$ Input: root = [1,2,3,4,5,6,7]
โ€บ Output: [[4],[2],[1,5,6],[3],[7]]
๐Ÿ’ก Note: Multiple nodes can have same (row,col). Node 1 at (0,0), nodes 5 and 6 both at (2,0). When nodes share position, sort by value: [1,5,6] not [1,6,5].
example_3.py โ€” Single Node
$ Input: root = [1]
โ€บ Output: [[1]]
๐Ÿ’ก Note: Single node at (0,0) forms one column with one element.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n log(n/w))

Single traversal O(n) + sorting within each column. Total sorting is O(n log(n/w)) where w is width, since nodes are distributed across columns

n
2n
โšก Linearithmic
Space Complexity
O(n)

Hash map storing all nodes grouped by column plus recursion stack

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • -1000 โ‰ค Node.val โ‰ค 1000
  • All node values are unique (except for duplicate position sorting test cases)
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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