Menu
CoddyTech

Construct Binary Tree from Preorder and Inorder Traversal

You get two arrays, preorder and inorder, that list the distinct values of the same binary tree. Preorder visits a node, then its left subtree, then its right subtree. Inorder visits the left subtree, then the node, then the right subtree.

Rebuild the tree and return it as an array in level order: the root at index 0, the children of index i at 2i+1 (left) and 2i+2 (right), and -1 for every empty spot. The array ends at the last node, with no trailing -1.

Function

buildTree(preorder: integer-array, inorder: integer-array) → integer-array
preorderinteger-array
the values in preorder: node, left subtree, right subtree
inorderinteger-array
the values in inorder: left subtree, node, right subtree
Returnsinteger-array
the tree in level order, with -1 for empty spots and no trailing -1

Constraints

  • 1 ≤ preorder.length ≤ 3000
  • inorder.length == preorder.length
  • 0 ≤ preorder[i] ≤ 104, and all values are distinct.
  • inorder holds the same values, and both arrays describe the same binary tree.
  • The depth of the tree is at most 14, so every index in the answer is below 214-1 = 16383.

Examples

Input
preorder = [7, 3, 0, 9, 4, 6]inorder = [0, 3, 9, 7, 4, 6]
Output
[7, 3, 4, 0, 9, -1, 6]
Explanation
Preorder starts with the root, 7. It sits at inorder position 3, so 0, 3, 9 go left and 4, 6 go right. 4 has only a right child, 6, so index 5 stays -1.
challenge icon

Follow-up

Can you rebuild the tree without recursion, in one pass over preorder with an explicit stack?

Reset code
def buildTree(preorder, inorder):
    # Write code here

Test #1

Test #2

Arguments

preorder = [7, 3, 0, 9, 4, 6]
inorder = [0, 3, 9, 7, 4, 6]

Expected Output

[7, 3, 4, 0, 9, -1, 6]