重建二叉树
分析
这道题难道是不难,主要是我一边写一边想事情,然后写完提交就过了。。。。直接在页面上写的,编译也是一次就过了
记录一下
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return getAns(preorder,inorder);
}
TreeNode * getAns(vector<int>& preorder, vector<int>& inorder){
if(!preorder.size())return NULL;
if(preorder.size()==1){
return new TreeNode(preorder[0]);
}
TreeNode * rt=new TreeNode(preorder[0]);
vector<int>lpre,rpre;
vector<int>lmid,rmid;
int preFlag=0,midFlag=0;
for(int i=0;i<inorder.size();i++){
if(inorder[i]==preorder[0]){
midFlag=1;
continue;
}
if(!midFlag){
lmid.push_back(inorder[i]);
}else{
rmid.push_back(inorder[i]);
}
}
int lsiz=lmid.size();
for(int i=1;i<preorder.size();i++){
if(i<1+lsiz){
lpre.push_back(preorder[i]);
}else{
rpre.push_back(preorder[i]);
}
}
rt->left=getAns(lpre,lmid);
rt->right=getAns(rpre,rmid);
return rt;
}
};