Problem · Tree

Bottom View of a Binary Tree

Learn this problem
MediumOracle logoOracleFULLTIMEONSITE INTERVIEW

Problem statement

You are given the root of a binary tree. Assign horizontal distance 0 to the root, distance d - 1 to the left child of a node at distance d, and distance d + 1 to its right child.

The bottom view contains one value for every horizontal distance: choose the node with the greatest depth at that distance. If two nodes at the same distance also have the same depth, choose the node visited later by a left-to-right level-order traversal. Return the selected values from the smallest horizontal distance to the largest.

Return an empty array when root is null.

Function

bottomView(root: TreeNode) → int[]

Examples

Example 1

root = [20,8,22,5,3,null,25,null,null,10,14]return = [5,10,3,14,25]

The visible nodes from left to right are 5, 10, 3, 14, and 25.

Example 2

root = [1,2,3,null,4,5,null]return = [2,5,3]

Nodes 4 and 5 share horizontal distance 0 and depth 2. Node 5 is visited later in left-to-right level order, so it wins the tie.

Example 3

root = []return = []

An empty tree has no horizontal distances in its bottom view.

Constraints

  • The tree contains between 0 and 10000 nodes.
  • -1000000000 <= Node.val <= 1000000000
  • The input uses a level-order array where null denotes a missing child.

More Oracle problems

drafts saved locally
public int[] bottomView(TreeNode root) {
  // write your code here
}
root[20,8,22,5,3,null,25,null,null,10,14]
expected[5,10,3,14,25]
checking account