Given a binary tree, return its bottom view from left to right.
The bottom view is the set of nodes visible when the tree is viewed from the bottom. Each node has a horizontal distance (HD) from the root: the root has HD 0, a left child has its parent's HD minus 1, and a right child has its parent's HD plus 1.
For each horizontal distance that occurs in the tree, the bottom view includes the node at the lowest level, meaning the deepest node with that HD. If several nodes share the same HD and the same lowest level, the rightmost one (the last one met in level-order traversal) is chosen.
Function Signature
def bottom_view(tree: list[int | None]) -> list[int]:
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.
-
Return one value per horizontal distance that occurs in the tree, ordered from the smallest HD to the largest.
Constraints
-
1 <= number of nodes <= 10^4
-
-1000 <= node value <= 1000
-
tree[0]
is not
None
.
Examples
Input: tree = [20, 8, 22, 5, 3, None, 25, None, None, 10, 14]
Output: [5, 10, 3, 14, 25]
Node 3 is the right child of 8 and has children 10 and 14, which sit at HD -1 and 1 below 8 and 22. Node 3 itself is at HD 0 and deeper than the root, while 5 and 25 are alone at HD -2 and 2.
Input: tree = [1, 2, 3]
Output: [2, 1, 3]
Each horizontal distance holds a single node: 2 at -1, 1 at 0 and 3 at 1.
Input: tree = [1, 2, 3, None, 4, 5, None, 6, 7]
Output: [6, 5, 7]
Node 2 has a right child 4, node 3 has a left child 5, and 4 has children 6 and 7. Nodes 4 and 5 are both at depth 2 and HD 0, so the rightmost one, 5, is chosen, and 6 and 7 are deeper than 2 and 3 at HD -1 and 1.