題目描述
#include <iostream>
#include <vector>
using namespace::std;
struct TreeNode{
int val;
TreeNode*left;
TreeNode*right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
class Solution {
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
if(pre.size() == 0 || in.size()==0) return NULL;
TreeNode*root = new TreeNode(pre[0]);
vector<int>Leftpre;
vector<int>Leftint;
vector<int>Rightpre;
vector<int>Rightint;
int i = 1;
int k = 0;
for( i = 1; i < pre.size(); i++){
if(in[i-1] == pre[0]){
Leftpre.push_back(pre[i]);
break;
}
Leftpre.push_back(pre[i]);
Leftint.push_back(in[i-1]);
}
for(int j = i; j < in.size(); j++){
Rightpre.push_back(pre[j]);
Rightint.push_back(in[j]);
}
root->left = reConstructBinaryTree(Leftpre, Leftint);
root->right = reConstructBinaryTree(Rightpre, Rightint);
return root;
}
};