Problem · Tree

Top View of a Binary Tree

Learn this problem
MediumCapillary Technologies logoCapillary TechnologiesFULLTIMEONSITE INTERVIEW

Problem statement

You are given a binary tree serialized in level order as levelOrder. Each entry is either an integer written as a string or "null".

Assign horizontal distance 0 to the root. A left child has its parent's distance minus 1, and a right child has its parent's distance plus 1. For each horizontal distance, the first node reached in level order is visible from above.

Return the visible node values from the smallest horizontal distance to the largest. Return an empty array for an empty tree.

Function

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

Examples

Example 1

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

The first visible nodes at horizontal distances -1, 0, 1, and 2 are 2, 1, 3, and 5.

Example 2

levelOrder = ["10","5","15","2","7","12","20"]return = [2,5,10,15,20]

The topmost values are read from the far-left horizontal distance through the far-right distance.

Example 3

levelOrder = []return = []

An empty tree has no visible nodes.

Constraints

  • 0 <= levelOrder.length <= 10^5
  • Every non-null entry is a valid 32-bit signed integer.
  • The serialization describes one valid binary tree in level order.

More Capillary Technologies problems

drafts saved locally
public int[] topView(String[] levelOrder) {
    // write your code here
}
levelOrder["1","2","3","null","4","null","5"]
expected[2,1,3,5]
checking account