Extract Sorted Values from Level-Order Encoded BST
Trees & GraphsAuto-graded · 18 test casesLast updated
Extract all valid integer elements from a level-order serialized binary search tree and return them in non-decreasing order.
You are given a list representing a Binary Search Tree (BST) serialized in level-order (breadth-first) layout. Missing nodes in the layout are represented by None (null).
Your task is to extract all valid node values present in the tree and return them as a list sorted in non-decreasing order.
Constraints
- The length of the input array is between
0and10^5. - Node values are integers within standard 32-bit signed bounds.
- The tree may contain duplicate values.
None(ornull) indicates a non-existent child node.
Examples
Example 1
Input: get_sorted_bst_values([4, 2, 6, 1, 3, 5, 7])
Output: [1, 2, 3, 4, 5, 6, 7]
Example 2
Input: get_sorted_bst_values([1, None, 2, None, 3])
Output: [1, 2, 3]
Hints
Hint 1
Recall that performing an in-order traversal of any valid Binary Search Tree yields its elements in sorted order.
Hint 2
Consider what set of elements is contained in the level-order representation vs. an in-order traversal.
Hint 3
Be careful to explicitly check for `None` values rather than relying on truthiness, as `0` is a valid node value.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
An in-order traversal of a valid Binary Search Tree yields all stored values in ascending order.
While one could explicitly reconstruct the binary tree from the level-order representation using a double-ended queue and then run an in-order traversal, notice that:
- Every node in the BST is present as a non-
Nonevalue in the level-order array. - The multiset of integer values in the tree is identical to the multiset of non-
Nonevalues in the input array. - Because the tree is a BST, its in-order traversal order is simply the sorted order of these non-
Nonevalues.
Therefore, we can simply filter out all None entries from the input list and sort the remaining integer values.
Correctness & Edge Cases
- Explicit
NoneCheck: We must checkval is not Nonerather thanif val, because0is a valid integer and evaluates toFalsein boolean contexts. - Duplicates: Sorting preserves duplicate values, matching the BST duplicate handling rules.
- Empty or Null Inputs: An empty list
[]or[None]correctly yields an empty output[].
Complexity
- Time Complexity: $\mathcal{O}(N \log N)$ where $N$ is the number of non-
Noneelements in the input list. In Python, Timsort will take $\mathcal{O}(N)$ time if the level-order array corresponds to a right-skewed tree (which is already sorted). - Space Complexity: $\mathcal{O}(N)$ to store and return the filtered list of node values.
def get_sorted_bst_values(level_order_list: list[int | None]) -> list[int]:
return sorted(val for val in level_order_list if val is not None)