//开始竟然忘了加return 了!! 152ms通过大的
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12
13 TreeNode *buildTree(vector<int> &inorder, int ib,int ie,vector<int> &postorder,int pb,int pe)
14 {
15 TreeNode *root=new TreeNode(0);
16 root->val=postorder[pe];
17
18 vector<int>::iterator proot=find(inorder.begin(),inorder.end(),postorder[pe]);
19 int pos=proot-inorder.begin();
20 int leftLen=pos-ib;
21 int rightLen=ie-pos;
22
23 if(pos>ib)
24 root->left=buildTree(inorder,ib,pos-1,postorder,pb,pb+leftLen-1);
25 if(pos<ie)
26 root->right=buildTree(inorder,pos+1,ie,postorder,pb+leftLen,pe-1);
27 return root;
28 }
29
30 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
31 // Start typing your C/C++ solution below
32 // DO NOT write int main() function
33 if(inorder.size()==0)
34 return NULL;
35 return buildTree(inorder,0,inorder.size()-1,postorder,0,inorder.size()-1);
36 }
37 };
//小的过了,大的内存不够
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
13 // Start typing your C/C++ solution below
14 // DO NOT write int main() function
15 if(inorder.size()==0)
16 {
17 return NULL;
18 }
19 if(inorder.size()==1)
20 {
21 TreeNode *root=new TreeNode(0);
22 root->val=inorder[0];
23 root->left=NULL;
24 root->right=NULL;
25 return root;
26 }
27
28 vector<int>::iterator p,q;
29 TreeNode *l,*r;
30 TreeNode *root=new TreeNode(0);
31 int ca,cb;
32 p=find(inorder.begin(),inorder.end(),postorder[postorder.size()-1]);
33 ca=p-inorder.begin();
34 cb=inorder.size()-(p-inorder.begin())-1;
35 vector<int> va(inorder.begin(),p);
36 vector<int> pa(postorder.begin(),postorder.begin()+ca);
37 vector<int> vb(p+1,inorder.end());
38 vector<int> pb(postorder.begin()+ca,postorder.begin()+ca+cb);
39
40 root->val=*p;
41 l=buildTree(va,pa);
42 r=buildTree(vb,pb);
43 root->left=l;
44 root->right=r;
45 return root;
46
47 }
48 };