FastPrepVertical Tree Traversal with Value Ties

Vertical Tree Traversal with Value Ties

Meta logoMeta● HardINTERNPHONE SCREEN
Learn

Problem statement

Return the vertical traversal of a binary tree. The root is at (row,column) = (0,0). A left child moves to (row+1,column-1), and a right child to (row+1,column+1).

Return columns from leftmost to rightmost. Within a column, order nodes by increasing row. When multiple nodes share both row and column, order their values increasingly.

Function

verticalTraversal(root: TreeNode) → int[][]

Examples

Example 1

root = [3,9,20,null,null,15,7]return = [[9],[3,15],[20],[7]]

Columns appear from leftmost to rightmost, with row order inside each column.

Example 2

root = [1,2,3,4,5,6,7]return = [[4],[2],[1,5,6],[3],[7]]

Values5 and6 share row and column, so5 comes first.

Example 3

root = [1,2,3,4,6,5,7]return = [[4],[2],[1,5,6],[3],[7]]

Swapping the two shared-coordinate nodes does not change their sorted output.

Constraints

  • The tree contains between 1 and 1000 nodes.
  • 0 <= Node.val <= 1000.

More Meta problems

See Meta hiring insights
public int[][] verticalTraversal(TreeNode root) {
    // Write your code here
}
root[3,9,20,null,null,15,7]
expected[[9],[3,15],[20],[7]]
Checking account…