Construct a Binary Tree from Postorder and Inorder
Given Postorder and Inorder traversals, construct the tree.
Examples:
Input :
in[] = {2, 1, 3}
post[] = {2, 3, 1}
Output : Root of below tree
1
/ \
2 3
Input :
in[] = {4, 8, 2, 5, 1, 6, 3, 7}
post[] = {8, 4, 5, 2, 6, 7, 3, 1}
Output : Root of below tree
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Solution:
classNode{intdata;Node left, right;publicNode(intdata){this.data = data;left = right =null;}}// Class Index created to implement pass by reference of IndexclassIndex{intindex;}classBinaryTree{/* Recursive function to construct binary of size nfrom Inorder traversal in[] and Preorder traversalpost[]. Initial values of inStrt and inEnd shouldbe 0 and n -1. The function doesn't do any errorchecking for cases where inorder and postorderdo not form a tree */Node buildUtil(intin[],intpost[],intinStrt,intinEnd, Index pIndex){// Base caseif(inStrt > inEnd)returnnull;/* Pick current node from Preorder traversal usingpostIndex and decrement postIndex */Node node =newNode(post[pIndex.index]);(pIndex.index)--;/* If this node has no children then return */if(inStrt == inEnd)returnnode;/* Else find the index of this node in Inordertraversal */intiIndex = search(in, inStrt, inEnd, node.data);/* Using index in Inorder traversal, construct left andright subtress */node.right = buildUtil(in, post, iIndex +1, inEnd, pIndex);node.left = buildUtil(in, post, inStrt, iIndex -1, pIndex);returnnode;}// This function mainly initializes index of root// and calls buildUtil()Node buildTree(intin[],intpost[],intn){Index pIndex =newIndex();pIndex.index = n -1;returnbuildUtil(in, post,0, n -1, pIndex);}/* Function to find index of value in arr[start...end]The function assumes that value is postsent in in[] */intsearch(intarr[],intstrt,intend,intvalue){inti;for(i = strt; i <= end; i++){if(arr[i] == value)break;}returni;}/* This funtcion is here just to test */voidpreOrder(Node node){if(node ==null)return;System.out.print(node.data +" ");preOrder(node.left);preOrder(node.right);}publicstaticvoidmain(String[] args){BinaryTree tree =newBinaryTree();intin[] =newint[]{4,8,2,5,1,6,3,7};intpost[] =newint[]{8,4,5,2,6,7,3,1};intn = in.length;Node root = tree.buildTree(in, post, n);System.out.println("Preorder of the constructed tree : ");tree.preOrder(root);}}
No comments:
Post a Comment