Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Postorder for the left and right, so postorder the last one for the root, after obtaining the root, in inorder can find the elements of the Zuozi and the subtree.
The problem can be decomposed into, finding roots, determining the elements of Zuozi and right subtrees. So, recursive solution.
Because Postorder stores the root node from left to right, the right subtree is constructed first.
/** * definition for binary tree * struct treenode { * int val; * TreeNode *left; * treenode *right; * treenode (int x) : val (x), left (null), right (null) {} * }; */class solution {public : int postindex; treenode *buildtree (vector<int> &inorder, vector<int> &postorder) { if (inorder.size () ==0| | Postorder.size () ==0) return NULL; postindex=postorder.size () -1; int stat=0; &nbsP; int end=postorder.size () -1; return foo (inorder,postorder,stat,end); } treenode* foo (Vector<int> &inorder,vector<int> &postorder,int stat,int end) { if (stat>end) return NULL; treenode* root=new treenode (0); root-> val=postorder[postindex]; postindex=postindex-1; int indexofroot=index (Inorder,root->val); if (iNdexofroot==-1) exit (0); if (stat==end) return root; root->right=foo (Inorder, Postorder,indexofroot+1,end); root->left=foo (Inorder, POSTORDER,STAT,INDEXOFROOT-1); return root; } int index (Vector<int> v,int val) { int i; for (i=0;i <v.size (); i++) if (v[i]==val) return i; return -1; } };
[Leetcode] Construct binary tree from inorder and postorder traversal