KatInterview

Extract Sorted Values from Level-Order Encoded BST

Trees & GraphsAuto-graded · 18 test cases
EasyAuto-gradedTrees & Graphstrees-graphsheaps-sortingbinary-search-tree

Last 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 0 and 10^5.
  • Node values are integers within standard 32-bit signed bounds.
  • The tree may contain duplicate values.
  • None (or null) 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.