/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param inorder int整型vector 中序遍历序列 * @param postorder int整型vector 后序遍历序列 * @return TreeNode类 */ TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { // write code here int n= inorder.size(),m = postorder.size(); return maketree(inorder,postorder,0,n-1,0,n-1); } TreeNode*maketree( vector<int> &id,vector<int> &pd,int l,int r,int j,int k) { if(l>r || j>k) return nullptr; if(l==r) return new TreeNode(id[l]); TreeNode * x = new TreeNode(pd[k]); int m = l; for(int i=l;i<=r;i++) { if(id[i] == pd[k]) { m = i; break; } } int left = k - (r-m); x->left = maketree(id,pd,l,m-1,j,left-1); x->right = maketree(id,pd,m+1,r,left,k-1); return x; } };