Problem · Tree
Vertical Order Traversal of a Binary Tree
Learn this problemProblem statement
Given the root of a binary tree, return its vertical traversal.
Place the root at row 0, column 0. A left child is at (row + 1, column - 1), and a right child is at (row + 1, column + 1).
Return columns from the smallest to the largest column. Within a column, order nodes by row from top to bottom; if multiple nodes share both row and column, order those nodes by value ascending.
Function
verticalTraversal(root: TreeNode) → List<List<Integer>>Examples
Example 1
root = [3,9,20,null,null,15,7]return = [[9],[3,15],[20],[7]]The four occupied columns are returned from leftmost to rightmost, with node 15 below the root in column zero.
Example 2
root = [1,2,3,4,5,6,7]return = [[4],[2],[1,5,6],[3],[7]]Nodes 5 and 6 share row two and column zero, so value order places 5 first.
Example 3
root = [1,2,3,4,6,5,7]return = [[4],[2],[1,5,6],[3],[7]]Even though traversal reaches 6 before 5, their shared coordinate is sorted by value.
Constraints
- The tree contains between
1and1000nodes. 0 <= Node.val <= 1000.