Top View of a Binary Tree
Updated
Problem statement
Given the root of a non-empty binary tree, return its top view from left to right.
Assign horizontal distance 0 to the root. A left edge decreases horizontal distance by 1, and a right edge increases it by 1. For every horizontal distance, the visible node is the node with minimum depth.
If two nodes have the same minimum depth and horizontal distance, choose the one reached first by a level-order traversal that enqueues each left child before its right child.
Function
topView(root: TreeNode) → int[]Examples
Example 1
root = [1,2,3,4,5,6,7]return = [4,2,1,3,7]Read in order, the green nodes give [4,2,1,3,7], the expected output.
The first visible nodes at horizontal distances -2 through 2 are 4, 2, 1, 3, 7.
Example 2
root = [1,2,3,null,4,5,null]return = [2,1,3]Read in order, the green nodes give [2,1,3], the expected output.
Nodes 4 and 5 share horizontal distance 0 below the root, so the root hides both.
Constraints
- The tree contains between
1and10^5nodes. -10^9 <= node.val <= 10^9
More InMobi Onsite Interview questions
- Russian Doll EnvelopesONSITE INTERVIEW · Seen Jul 2026
- Minimum and Maximum with Optimal ComparisonsONSITE INTERVIEW · Seen Dec 2025
- Minimum Edges to Connect All ComponentsONSITE INTERVIEW · Seen Dec 2025
- Shortest Path Visiting All NodesONSITE INTERVIEW · Seen Sep 2025
- Maximum Sum of Non-Adjacent Tree NodesONSITE INTERVIEW · Seen Jan 2022
- Word SquaresONSITE INTERVIEW · Seen Jan 2022
- Maximum Length Pair ChainONSITE INTERVIEW · Seen Jul 2021
- Maximum XOR Between Two ArraysONSITE INTERVIEW · Seen May 2021
- Trapping Rain WaterONSITE INTERVIEW · Seen May 2021
- Validate Binary Search TreeONSITE INTERVIEW · Seen May 2021
Similar questions at other companies
- Delete Nodes and Return Forest RootsGoogle · ONSITE INTERVIEWGoogle interview questions
- Team Cost Under a ManagerRippling · PHONE SCREENRippling interview questions
- Diagonal Traversal of a Binary TreeAmazon · ONSITE INTERVIEW
- Render an Org Chart and Find Skip-Level PairsSnap Inc. · ONSITE INTERVIEWSnap Inc. interview questions
- N-ary Index-Path Encoder and DecoderBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- JSON Path Lookup with Implicit Array WildcardsMongoDB · ONSITE INTERVIEWMongoDB interview questions
- Group Identical Tree LevelsSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Merge N-Ary Trees by KeyLinkedIn · PHONE SCREEN · ONSITE INTERVIEWLinkedIn interview questions
- Filesystem Hash TreeCursor · PHONE SCREEN · ONSITE INTERVIEWCursor interview questions
- Bottom View of a Binary TreeOracle · PHONE SCREEN · ONSITE INTERVIEWOracle interview questions