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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code