You are given a binary tree as a level-order list, with None marking a missing child. Return three views of the tree in one dictionary:
-
"top_view"
: the values visible when the tree is viewed from the top, ordered from left to right by horizontal distance from the root.
-
"bottom_view"
: the values visible when the tree is viewed from the bottom, ordered from left to right by horizontal distance.
-
"level_order"
: the node values grouped by level, from top to bottom and left to right within each level.
The root has horizontal distance 0. A left child has its parent's distance minus 1, and a right child has its parent's distance plus 1.
Function Signature
def binary_tree_views(tree: list[int | None]) -> dict[str, list]:
Rules
-
tree
uses the standard compact level-order encoding. The first entry is the root. After it, the entries come in pairs: the left child and then the right child of each real node, taking the real nodes in the order they appear in the list. A
None
entry has no children listed for it, and trailing
None
values may be left off.
-
Level order goes by depth from the root, and left to right within a depth.
-
Top view: for each horizontal distance, the node that comes first in level order.
-
Bottom view: for each horizontal distance, the node that comes last in level order. When two nodes share both a horizontal distance and a level, the one further right wins.
-
Each view holds one value per horizontal distance that occurs in the tree, listed from the smallest distance to the largest.
Constraints
-
1 <= number of nodes <= 10^4
-
-1000 <= node value <= 1000
-
tree[0]
is not
None
.
Examples
Input: tree = [1, 2, 3, 4, 5, 6, 7]
Output: {"top_view": [4, 2, 1, 3, 7], "bottom_view": [4, 2, 6, 3, 7], "level_order": [[1], [2, 3], [4, 5, 6, 7]]}
This is a full tree with three levels. Nodes 1, 5 and 6 all sit at horizontal distance 0: the top view keeps 1 because it comes first in level order, and the bottom view keeps 6 because it comes last.
Input: tree = [1, 2, 3, None, 5, None, 7]
Output: {"top_view": [2, 1, 3, 7], "bottom_view": [2, 5, 3, 7], "level_order": [[1], [2, 3], [5, 7]]}
Node 2 has only a right child 5, and node 3 has only a right child 7. Node 5 lands at horizontal distance 0, so it replaces 1 in the bottom view while the top view still shows 1.
Input: tree = [1, 2, 3, None, 4, None, None, None, 5]
Output: {"top_view": [2, 1, 3], "bottom_view": [2, 4, 5], "level_order": [[1], [2, 3], [4], [5]]}
Here 2 has a right child 4, 3 is a leaf, and 4 has a right child 5, so 4 sits at horizontal distance 0 and 5 at distance 1. From the bottom, 4 covers the root and 5 covers node 3.