854. Top View of Binary Tree

EasyTreesBinary TreeBFSHash

Given the root of a binary tree, return its top view — the nodes visible when the tree is viewed from directly above, ordered left to right by horizontal distance. The root has horizontal distance 0; a left child is one less, a right child one more. For each horizontal distance the topmost node (first reached in level order) is visible. The tree is given as a level-order array.

Input: A level-order array of the tree.

Output: Array — top-view node values, left to right.

Examples

Example 1
Input: [1,2,3,4,5,6,7]
Output: [4,2,1,3,7]
Explanation: One node per horizontal distance, topmost first.
Example 2
Input: [1]
Output: [1]
Explanation: Single node.
Example 3
Input: []
Output: []
Explanation: Empty tree.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →