Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
preorder[preL] is always the root of the current subtreeleftSize = inMid - inL elements go to the left subtreebuild(left range) then build(right range)
preorder[0] is always the root.
Finding it in inorder splits the array into left and right subtrees.
The number of elements to the left
(leftSize = inMid − inL) tells us exactly which
portion of preorder belongs to the left subtree:
pre[preL+1 .. preL+leftSize].
Everything after belongs to the right. A HashMap pre-indexes
inorder values for O(1) lookup, giving overall
O(n) time.
Trying every possible tree shape and checking both traversals is hopeless. The two traversals carry complementary information, and together they fix the tree.
The first value of the preorder is always the root. Find that root in the inorder, and everything to its left belongs to the left subtree. Everything to its right belongs to the right subtree. The size of the left part tells you how many preorder values belong to the left subtree. Use a hash map from value to inorder index, so each lookup is O(1).
Preorder gives the root, inorder gives the split. Build left before right, so the preorder pointer stays in sync.
Run the animation above on your own input, or watch the 2:16 video explanation of Construct Binary Tree from Preorder and Inorder Traversal with a dry run and Java code.