For this problem just need to know the structure of both traversal.
1. It's hard-to-find the root node in the Inorder traversal but it's easy in postorder. The last one on post order is the root.
2. At same time, you can not be a figure out of what's the boundary for left branch and right branch in post order. But the can do it in inorder.
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: ATreeNode *gettree (vector<int> &iv, vector<int> &PV,intIstintIedintPstintPED) { - if(Ist > IED)returnNULL; - intCurrent =-1, Len =0; the for(inti = ist; I <= IED; i++) { - if(pv[ped] = =Iv[i]) { -Current =i; - Break; + } - } +Len = current-ist; ATreeNode *root =NewTreeNode (pv[ped]); atRoot->left = Gettree (iv, PV, ist, current-1, PST, pst+len-1); -Root->right = Gettree (iv, PV, current+1, IED, Pst+len, ped-1); - } -TreeNode *buildtree (vector<int> &inorder, vector<int> &postorder) { - if(inorder.size () = =0|| Inorder.size ()! = Postorder.size ())returnNULL; - returnGettree (Inorder, Postorder,0, Inorder.size ()-1,0, Postorder.size ()-1); in } -};
Leetcode–refresh–construct Binary Tree from inorder and Postorder traversal