Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Top View of Binary Tree

Medium Acceptance 60.21% Points 30

You are given the root of a binary tree. Your task is to return the top view of the tree.

The top view consists of the nodes visible when the tree is viewed from directly above.

For each horizontal distance from the root:

  • Only the topmost node is visible.
  • If multiple nodes share the same horizontal distance, the node encountered first from the top is chosen.
  • The result should be returned from the leftmost horizontal distance to the rightmost.
Examples
Example 1

image Input: root = [1,2,3,4,5,6,7]
Output: [4,2,1,3,7]
Explanation: Assigning horizontal distances relative to the root, the topmost node at each distance forms the top view from left to right.

Example 2

image Input: root = [1,2,3]
Output: [2,1,3]
Explanation: Node 2 is at distance -1, node 1 at 0, and node 3 at +1.

Example 3

image Input: root = []
Output: []
Explanation: An empty tree has an empty top view.

Constraints
    • 0 = Number of nodes = 104
    • -10? = Node.data = 10?
Topics
Tree Traversal Binary Tree
Companies
IBM Intuit
Added 08 Aug 2026 60.21% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5 6 7
4 2 1 3 7