/** 106. Construct Binary Tree from inorder and postorder traversal * 11.21 by Mingyang * Becuase k are not the length, it It need to – (instart+1) to get the length * Note that K cannot be used as the index of the postorder and must be added to the distance.*/ PublicTreeNode BuildTree2 (int[] inorder,int[] postorder) { intInstart = 0; intInend = inorder.length-1; intPoststart = 0; intPostend = postorder.length-1; returnbuildTree2 (inorder, Instart, Inend, Postorder, poststart,postend); } PublicTreeNode BuildTree2 (int[] inorder,intInstart,intInend,int[] Postorder,intPoststart,intpostend) { if(Instart > Inend | | poststart >postend)return NULL; intRootvalue =Postorder[postend]; TreeNode Root=NewTreeNode (Rootvalue); intK = 0; for(inti = 0; i < inorder.length; i++) { if(Inorder[i] = =rootvalue) {k=i; Break; }} root.left= BuildTree2 (Inorder, Instart, k-1, Postorder, Poststart, Poststart+ K-(Instart + 1)); //becuase k is isn't the length, it it need to – (instart+1) to get the length//k is only related to inorder, can not bring postorder to use, so it is notRoot.right = BuildTree2 (inorder, K + 1, inend, Postorder, Poststart + K-instart, postEnd-1); //Poststart+k-instart = poststart+k-(instart+1) +1 returnRoot; }
106. Construct Binary Tree from inorder and Postorder traversal