由前序和中序重建
题目链接
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8e299d0988ef262f647d59ee33d009f9.png#pic_center)
class Solution {
typedef vector<int>::iterator vit;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return recursionBuild(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
}
TreeNode* recursionBuild(vit preBegin, vit preEnd,vit inBegin, vit inEnd)
{
if(inEnd==inBegin) return NULL;
TreeNode* cur = new TreeNode(*preBegin);
auto root = find(inBegin,inEnd,*preBegin);
cur->left = recursionBuild(preBegin+1,preBegin+1+(root-inBegin),inBegin,root);
cur->right = recursionBuild(preBegin+1+(root-inBegin),preEnd,root+1,inEnd);
return cur;
}
};
由中序和后序重建
题目链接
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/84369baa0190a513a5289abb2d3b842e.png#pic_center)
class Solution {
typedef vector<int>::iterator it;
TreeNode* rebuild(it inbegin,it inend,it postbegin,it postend){
if(inbegin==inend) return nullptr;
TreeNode* cur=new TreeNode(*(postend-1));
auto root=find(inbegin,inend,*(postend-1));
cur->left=rebuild(inbegin,root,postbegin,postbegin+(root-inbegin));
cur->right=rebuild(root+1,inend,postbegin+(root-inbegin),(postend-1));
return cur;
}
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return rebuild(inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
}
};