Vertical Order Traversal of a Binary Tree

Hard

Description

Return the vertical order traversal of a binary tree. Nodes are ordered by column, then row, then value.

Examples

Input:root = [3,9,20,null,null,15,7]
Output:[[9],[3,15],[20],[7]]
Explanation:

Assign column 0 to root (3). Left child 9 is at column -1, right child 20 is at column +1. Node 15 (left child of 20) is at column 0, node 7 (right child of 20) is at column +2. Grouping by column from left to right: column -1 has [9], column 0 has [3,15] (3 at row 0, 15 at row 2), column +1 has [20], column +2 has [7].

Input:root = [1,2,3,4,5,6,7]
Output:[[4],[2],[1,5,6],[3],[7]]
Explanation:

This complete binary tree demonstrates multiple nodes at the same column and row. Column -2: node 4, Column -1: node 2, Column 0: nodes 1,5,6 (ordered by row then value), Column 1: node 3, Column 2: node 7.

Input:root = [5,1,8,null,2,null,null,null,3]
Output:[[1],[5,2],[8]]
Explanation:

Tree structure: 5 is root (col 0, row 0), 1 is left child (col -1, row 1), 8 is right child (col +1, row 1), 2 is right child of 1 (col 0, row 2). Grouping by column from left to right: column -1 contains [1], column 0 contains [5, 2] ordered by row (5 at row 0, 2 at row 2), column +1 contains [8].

Constraints

  • 1 ≤ number of nodes ≤ 1000

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!