使用递归:
class Solution {
public:
TreeNode * buildTree(vector<int> &inorder, vector<int> &postorder) {
// write your code here
if (inorder.size() == 0) return NULL;
int root = postorder[postorder.size() - 1];
TreeNode* this_root= new TreeNode(root);
int i;
for (i = 0; i < inorder.size(); i++)
if (inorder[i] == root) break;
vector<int>new_inorder;
vector<int>new_postorder;
new_inorder.assign(inorder.begin(), inorder.begin() + i);
new_postorder.assign(postorder.begin(), postorder.begin() + i);
this_root->left = buildTree(new_inorder, new_postorder);
new_inorder.assign(inorder.begin() + i + 1, inorder.end());
new_postorder.assign(postorder.begin() + i, postorder.end() - 1);
this_root->right = buildTree(new_inorder, new_postorder);
return this_root;
}
};
以上为了方便,直接在原方法上写的递归,所以需要多次重建两个vector,时间和空间占用得都比较多。还可以采用重写一个递归的方法:
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode *buildTree(vector<int> &inorder, int iLeft, int iRight, vector<int> &postorder, int pLeft, int pRight) {
if (iLeft > iRight || pLeft > pRight) return NULL;
TreeNode *cur = new TreeNode(postorder[pRight]);
int i = 0;
for (i = iLeft; i < inorder.size(); ++i) {
if (inorder[i] == cur->val) break;
}
cur->left = buildTree(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1);
cur->right = buildTree(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1);
return cur;
}
};