FastPrepVertical Order Traversal of a Binary Tree

Vertical Order Traversal of a Binary Tree

Bloomberg LP logoBloomberg LP● HardNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

You are given a binary tree serialized as a level-order string array levelOrder. Each non-null token is a signed decimal integer, and "null" denotes a missing child.

Place the root at row 0, column 0. A left child is at row r + 1, column c - 1, and a right child is at row r + 1, column c + 1.

Return the values grouped from the smallest column to the largest. Within each column, order nodes by increasing row. When nodes share both row and column, order their values from smallest to largest.

Function

verticalTraversal(levelOrder: String[]) → int[][]

Examples

Example 1

levelOrder = ["3","9","20","null","null","15","7"]return = [[9],[3,15],[20],[7]]

Columns run from -1 through 2; values are ordered by row inside each column.

Example 2

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

Values 6 and 5 share row 2 and column 0, so they appear as 5, 6.

Example 3

levelOrder = []return = []

An empty tree has no vertical columns.

Constraints

  • 0 <= non-null node count <= 100000
  • Every non-null token represents a signed 32-bit integer.
  • levelOrder is a valid level-order serialization using "null" markers.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int[][] verticalTraversal(String[] levelOrder) {
    // Write your code here.
}
levelOrder["3","9","20","null","null","15","7"]
expected[[9],[3,15],[20],[7]]
Checking account…