Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-101

Tree Top View Keys

Problem

Return the top view of a binary tree as a list of keys.

tree is a level-order list with None marking missing nodes. Assign horizontal distances to nodes (root 0, left child one less, right child one more); the first node seen at each distance in a breadth-first traversal is the top view.

Return the visible values ordered from the leftmost distance to the rightmost.

Hint

BFS guarantees that the first node seen at a horizontal distance is the topmost.

Test cases

case 1
in: [[1,2,3,4,5,6,7]]
expected: [4,2,1,3,7]
case 2
in: [[]]
expected: []
case 3
in: [[1,2]]
expected: [2,1]
case 4
in: [[1,null,2,null,null,3]]
expected: [1,2]
Starter codePython
def top_view(tree):
    # Your code here
    pass

4 test cases · run your code against them in the editor