The algorithm:
Root = first element of preorder
Find root's index in inorder
Split inorder into left and right parts
Split preorder based on this (by counting elements)
Recurse
def buildTree(preorder, inorder):
if not preorder:
return null
rootVal = preorder[0]
root = TreeNode(rootVal)
mid = inorder.index(rootVal)
root.left = buildTree(preorder[1:mid+1], inorder[:mid])
root.right = buildTree(preorder[mid+1:], inorder[mid+1:])
return root
Optimization: use a hash map for index lookup in inorder. Pass indices instead of slicing arrays.
Time: with hash map. Space: .