/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==0){
return NULL;
}
if(preorder.size()==1){
TreeNode* root=new TreeNode(preorder[0]);
}
TreeNode* head=new TreeNode(preorder[0]);//先序序列第一个为根节点
vector<int> newIn_left;
vector<int> newIn_right;
int f=0;
/**
在中序序列中,把根节点左边和右边的序列都拿出来
*/
for(int i=0;i<preorder.size();i++){
if(inorder[i]!=preorder[0]&&f==0){
newIn_left.push_back(inorder[i]);
// cout<<"newInleft "<<inorder[i]<<endl;
}
if(f==1){
//cout<<"newInright "<<inorder[i]<<endl;
newIn_right.push_back(inorder[i]);
}
if(inorder[i]==preorder[0]){
f=1;
}
}
//cout<<newIn_left.size()<<endl;
vector<int> newPre_left;
vector<int> newPre_right;
/**
在前序序列中,把根节点左边和右边的序列都拿出来
*/
for(int i=1;i<preorder.size();i++){
if(i<1+newIn_left.size()){
//cout<<"newPreleft "<<preorder[i]<<endl;
newPre_left.push_back(preorder[i]);
}else{
//cout<<"newPreRihjt "<<preorder[i]<<endl;
newPre_right.push_back(preorder[i]);
}
}
head->left=buildTree(newPre_left,newIn_left);
head->right=buildTree(newPre_right,newIn_right);
return head;
}
};
标签:preorder,right,TreeNode,int,中序,vector,二叉树,前序,left
From: https://www.cnblogs.com/lwx11111/p/16747581.html