Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Top View of Binary Tree

Medium Acceptance 60.21% Points 30.00

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?
Companies
IBM Intuit
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions