The problem. Given the root of a binary tree, return its top view: the nodes you would see looking down on the tree from above, from the leftmost column to the rightmost. Give the root column 0; a left child is one column to the left (−1), a right child one column to the right (+1). In each column you see only the highest node. (If two nodes share a column and a level, the one further left in level order counts.)
Input: root = [1, 2, 3, 4, 5, 6, 7] Output: [4, 2, 1, 3, 7]
Input: root = [1, 2, 3, null, 4, null, null, null, 5, null, 6] Output: [2, 1, 3, 6]Each node gets two coordinates: its column (from the left/right moves) and its depth. The top view is, for each column, the node with the smallest depth. The approaches differ in how they find "smallest depth per column" and how they put the columns in order.
Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come
Was this helpful?