Given a binary tree, return a list containing the values of all leaf nodes in left-to-right order.
A leaf node is a node that has neither a left nor a right child.
Function Signature
def leaf_values(tree: list[int | None]) -> list[int]:
...
Rules
-
The tree is given as a level-order list.
None
marks a missing child, and a missing node has no entries for its own children, so
[1, None, 2]
is a root 1 whose only child is a right child 2. Trailing
None
values may be left out.
-
Left-to-right order is the order in which a depth-first traversal that visits the left subtree before the right subtree reaches the leaves. For any node, every leaf in its left subtree comes before every leaf in its right subtree, whatever their depths.
Constraints
-
1 <= number of nodes <= 10^4
-
-10^4 <= node value <= 10^4
Examples
Input: tree = [1, 2, 3, 4, 5, None, 6]
Output: [4, 5, 6]
Node 2 has children 4 and 5, and node 3 has only a right child 6. Those three nodes have no children, and reading them from left to right gives 4, 5, 6.
Input: tree = [10]
Output: [10]
A single node has no children, so it is itself a leaf.
Input: tree = [5, 3, 8, 1, None, None, 9, None, 2]
Output: [2, 9]
The leaves are 2 (the right child of 1, which is the left child of 3) and 9 (the right child of 8). Leaf 2 is one level deeper than leaf 9, but it sits in the root's left subtree, so it comes first.