KatInterview

Rebuild a Search Tree from Its Preorder Listing

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbinary-search-treestackpreorder

Last updated

Rebuild a binary search tree from its preorder listing of distinct integers in linear time, then report it in level order with null placeholders. Tests stack-based construction and BFS serialization.

Rebuild a Search Tree from Its Preorder Listing

You are given a list of distinct integers that is the preorder traversal (node, then left subtree, then right subtree) of some binary search tree (BST). Reconstruct that exact tree and return it in level-order serialization.

In a BST, every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger.

Output format

Return a list describing the tree level by level, from left to right:

  • Start with the root.
  • For every real node, in level-order, append its value and then enqueue both of its children, using None for a child that does not exist.
  • None entries are visited too, and they contribute a None to the output, but they have no children of their own.
  • After the traversal, remove all trailing None values from the list.
  • If the input is empty, return an empty list [].

For instance, a chain where each node only has a right child is written as [1, None, 2, None, 3], because each node's missing left child appears as None.

Notes

  • Do not rebalance the tree or sort the values. The tree you return must be the one that the given preorder describes.
  • The tree may be completely lopsided (a single long chain), so be careful with very deep recursion.

Task

Implement rebuild_bst_level_order(preorder) which takes the preorder list and returns the level-order serialization described above.

Constraints

  • 0 <= len(preorder) <= 100,000
  • All values are unique signed 32-bit integers.
  • The input is guaranteed to be a valid preorder traversal of some BST.
  • An empty input returns [].

Examples

Example 1

Input: rebuild_bst_level_order([8, 5, 1, 7, 10, 12])

Output: [8, 5, 10, 1, 7, None, 12]

Example 2

Input: rebuild_bst_level_order([1, 2, 3, 4, 5])

Output: [1, None, 2, None, 3, None, 4, None, 5]

Example 3

Input: rebuild_bst_level_order([4, 2, 1, 3, 6, 5, 7])

Output: [4, 2, 6, 1, 3, 5, 7]

Hints

Hint 1

Every value after the first must be a child of a node you have already seen. Think about which already-seen nodes can still accept a new child.

Hint 2

Keep a stack of nodes that are still waiting for a right child. If the next value is smaller than the top, it becomes the top's left child. Otherwise pop while the top is smaller than the value.

Hint 3

The last node popped is the parent of the new value (as its right child). Finally, do a BFS that also enqueues missing children as None, and strip trailing Nones from the result.