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:
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.
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.
Input: root = []
Output: []
Explanation: An empty tree has an empty top view.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 2 3 4 5 6 7
4 2 1 3 7
10 5 15 2 7 12 20
2 5 10 15 20