Skip to the code
cf.
+25 XP

#361 Sorted Tree From a Preorder Walk

medium

A saved search index was written as the preorder walk of a binary search tree (node, left subtree, right subtree). Values are unique. That alone is enough to rebuild a search tree, because its inorder walk is just the values sorted.

Write restoreIndex(preorder) that rebuilds the binary search tree and returns its root. Try to do it in O(n) time. An empty list gives an empty tree.

Example 1

Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

8 is the root; 5, 1, 7 are smaller, so they form the left subtree.

Example 2

Input: preorder = [1,3]
Output: [1,null,3]

3 is bigger than 1, so it goes right.

Constraints

  • 0 <= preorder.length <= 10^4
  • Values are unique and come from a real search tree.

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).