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
function buildTree(preorder, inorder):
if preorder is empty:
return null
rootVal = preorder[0]
root = TreeNode(rootVal)
mid = indexOf(inorder, rootVal)
root.left = buildTree(preorder[1..mid], inorder[0..mid-1])
root.right = buildTree(preorder[mid+1..end], inorder[mid+1..end])
return root
Optimization: use a hash map for index lookup in inorder. Pass indices instead of slicing arrays.
Time: with hash map. Space: .