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.
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.
Input: preorder = [1,3] Output: [1,null,3]
3 is bigger than 1, so it goes right.
0 <= preorder.length <= 10^4Trees 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.
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).
I'm here to help with #361 Sorted Tree From a Preorder Walk. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.