Menu
CoddyTech

Vertical Order Traversal of a Binary Tree

A binary tree is stored in the array root in heap order: the root is at index 0, the children of index i are at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries.

The root is in column 0; a left child is one column left of its parent, a right child one column right. Return one list per column, from left to right. Inside a column, list nodes top to bottom, and nodes that share a column and a depth in increasing order of value.

Function

verticalTraversal(root: integer-array) → integer-2d-array
rootinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-2d-array
one list of values per column, leftmost column first, each from top to bottom

Constraints

  • 1 ≤ root.length ≤ 32767
  • Each root[i] is -1 or a value with 0 ≤ root[i] ≤ 5000, and no value appears twice.
  • root[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the tree has at most 14 levels.

Examples

Input
root = [5, 2, 9, 4, 7, 1, 6]
Output
[[4], [2], [5, 1, 7], [9], [6]]
Explanation
Column 0 holds the root 5, then 7 and 1 two levels down. Those two share column and depth, so 1 comes before 7, even though 7 is further left.
challenge icon

Follow-up

Every value is at most 5000. Can you use that to drop the comparison sort and finish in O(n + 5000) time?

Reset code
def verticalTraversal(root):
    # Write code here

Test #1

Test #2

Test #3

Argument

root = [5, 2, 9, 4, 7, 1, 6]

Expected Output

[[4], [2], [5, 1, 7], [9], [6]]