How can I construct a tree given its inorder and preorder traversal? I am just looking for an efficient algorithm.
A blatant copy and paste from Sun's (Oracle now, I guess...) forum:
Question:
Can anybody help me on how to construct Binary tree from inorder and postorder traversals,i just want to know the algorithm so that i can apply it.Answer:
Letp_1,p_2...p_nbe the postorder traversal and leti_1,i_2...i_nbe the inorder traversal. From the postorder traversal we know that the root of the tree isp_n. Find this element in the inorder traversal, sayi_1,i_2...i_k-1p_ni_k+1...i_n. From the inorder traversal we find all the elements in the left subtree, i.e.i_1,i_2...i_k-1and in the right subtree, i.e.i_k+1...i_nrespectively.Remove element
p_n(and elementi_k==p_n). Find the rightmost elementp_jinp_1,p_2...p_j...p_n-1wherep_jis an element ini_1,i_2...i_k-1. This is the root of the left subtree of the original tree. Splitp_1,p_2...p_jandp_j+1...p_n-1andi_1,i_2...i_k-1andi_k+1...i_n. Now you have two subsequences representing the postorder and inorder traversal of the two subtrees of the original tree.
Author: JosAH.
I've implemented the algorithm once following Jos' instructions, and it worked perfectly!