Q. Give the algorithm to build a binary tree where the yields of preorder and post order traversal are given to us.
Ans.
Tree cannot be built using the Preorder and Postorder traversal of the binary
tree. For this Inorder traversal has to be given to us.
Hence to construct a tree using Inorder and preorder traversal (as an example, traversals of Q 104 are used), the algorithm is stated follows:
The tree T is drawn from the root in the downward direction as follows:
1) The root of T is obtained by selecting the first node in its preorder. Hence G is the root of the node.
2) The left child of the node G is obtained as by. First using the inorder of T to find the node in the left subtree LTA of G. Thus LTA comprises of the nodes B,Q,A,C,K,F. Then the left child of G is obtained by selecting the first node in the preorder of LTA (which appears in the Preorder of T). Hence B is the left son of G.
3) Likewise the right subtree RTA of G comprises of the nodes P, D, E, R, H and P is the root of RTA, which means P is the right child of G.
Repeating the above steps with the each new node, we finally get the required tree.