Given Inorder and Postorder traversal of a tree, construct the binary tree.
Constructs a binary tree based on the middle sequence (left root right) and post-order traversal of the tree
Reference: http://www.cnblogs.com/remlostime/archive/2012/10/29/2744738.html
The last element of the post-order traversal is the root node, which divides the middle sequence traversal array into two arrays through the root node, which is a collection of Saozi right sub-tree nodes, which are recursively called
Use the subscript here to save space
1 Public classSolution {2 PublicTreeNode Buildtree (int[] inorder,int[] postorder) {3 TreeNode Root;4 if(0 = =inorder.length)5 return NULL;6 Else 7 returnCreatetree (inorder, postorder, 0, inorder.length-1, 0, Postorder.length-1);8 9 }Ten PrivateTreeNode Createtree (int[]inorder,int[] Postorder,intInstart,intInend,intPoststart,intpostend) { One if(Instart >inend) A return NULL; - intValue_root = Postorder[postend];//the value of the root node - intindex = 0;//The index value of the root node in the middle sequence traversal the for(inti = Instart; I <= inend; i++) {//find the index value of the root node in the final traverse - if(Postorder[postend] = =Inorder[i]) { -index =i; - Break; + } - } + intLength_lefttree = Index-instart;//Length of Zuozi ATreeNode lefttreeroot = Createtree (inorder, Postorder, Instart, Index-1, Poststart, Poststart + length_lefttree-1); atTreeNode righttreeroot = Createtree (inorder, Postorder, index + 1, inend, Poststart + length_lefttree, postEnd-1); - -TreeNode root =NewTreeNode (value_root); - -Root.left =Lefttreeroot; -Root.right =Righttreeroot; in - returnRoot; to } +}
Construct Binary Tree from inorder and Postorder traversal