Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
structTreeNode {intVal; TreeNode*Left ; TreeNode*Right ; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: TreeNode*buildtree (vector<int> &inorder, vector<int> &postorder) { //Start Typing your/C + + solution below//Do not write int main () functionRoot =NULL; if(Inorder.empty ())returnRoot; Root=NewTreeNode (0); Buildsubtree (Inorder,postorder,0, Inorder.size ()-1,0, Postorder.size ()-1, Root); returnRoot; } voidBuildsubtree (vector<int> &inorder, vector<int>&postorder,intInstartpos,intInendpos,intPoststartpos,intPostendpos,treenode *CurrentNode) {CurrentNode->val = Postorder[postendpos];//the last node of the post-post traversal is the root node//find root position in inorder vector intInrootpos; for(inti = Instartpos; I <= Inendpos; i++) { if(Inorder[i] = =Postorder[postendpos]) {Inrootpos=i; Break; } } //Right Tree: Is the part of the middle sequence that follows the root node, corresponding to the part of the same length before the root node is traversed . intNewpostpos = Postendpos-max (Inendpos-inrootpos,0); if(inrootpos<Inendpos) {CurrentNode->right =NewTreeNode (0); Buildsubtree (Inorder,postorder,inrootpos+1, inendpos,newpostpos,postendpos-1,currentnode->Right ); } //Lefttree: Is the part of the middle sequence that precedes the root node, corresponding to the post-order traversal of the same length from the beginning if(inrootpos>Instartpos) {CurrentNode->left =NewTreeNode (0); Buildsubtree (Inorder,postorder,instartpos,inrootpos-1, poststartpos,newpostpos-1,currentnode->Left ); } }Private: TreeNode*root;};
106. Construct Binary tree from Inorder and postorder traversal (Tree; DFS)