长度居然是唯一的确定作用子树的方法,因为左右子树的左点和右点可能不存在,而找根结点又不是那么方便,而长度居然成了唯一靠谱的了。
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* f(vector<int> &inorder, vector<int> &postorder,int l1,int r1, int l2, int r2);
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
return f(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
}
TreeNode* f(vector<int> &inorder, vector<int> &postorder,int l1,int r1, int l2, int r2) {
if (l1>r1||l2>r2) return NULL;
int i=l1,cnt = 0;
for (;inorder[i]!=postorder[r2]&&i<=r1;i++,cnt++);
if(i>r1) return NULL;
TreeNode* head = new TreeNode(postorder[r2]);
head->left = f(inorder,postorder,l1,i-1,l2,l2+cnt-1);
head->right = f(inorder,postorder,i+1,r1,l2+cnt,r2-1);
return head;
}
void pri(TreeNode* h) {
if (h) {
cout<<h->val<<" ";
pri(h->left);
pri(h->right);}
}
int main() {
vector<int> v1,v2;
v1.push_back(1);v1.push_back(2);v1.push_back(3);
v2.push_back(3);v2.push_back(2);v2.push_back(1);
TreeNode* h =buildTree(v1,v2);
pri(h);
}