/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildCore(vector<int> &preorder, int prebeg, int preend,
vector<int> &inorder, int inbeg, int inend) {
int root_data = preorder[prebeg];
TreeNode* root = new TreeNode(root_data);
if (prebeg == preend) {
return root;
}
int leftSize=0, rightSize=0;
for (int i = inbeg; i < inend && inorder[i]!=root_data; i++) {
leftSize++;
}
/*if (leftSize==0 && rightSize==0) {
return NULL;
}*/
rightSize = preend-prebeg-leftSize;
TreeNode* left = NULL;
TreeNode* right = NULL;
if (leftSize!=0) {
left = buildCore(preorder, prebeg+1, leftSize+prebeg, inorder, inbeg, leftSize+inbeg-1);
}
if (rightSize!=0) {
right = buildCore(preorder, prebeg+leftSize+1, preend, inorder, leftSize+inbeg+1, inend);
}
root->left = left;
root->right = right;
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (preorder.empty() && inorder.empty()) {
return NULL;
}
return buildCore(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
};
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildCore(vector<int> &preorder, int prebeg, int preend,
vector<int> &inorder, int inbeg, int inend) {
int root_data = preorder[prebeg];
TreeNode* root = new TreeNode(root_data);
if (prebeg == preend) {
return root;
}
int leftSize=0, rightSize=0;
for (int i = inbeg; i < inend && inorder[i]!=root_data; i++) {
leftSize++;
}
/*if (leftSize==0 && rightSize==0) {
return NULL;
}*/
rightSize = preend-prebeg-leftSize;
TreeNode* left = NULL;
TreeNode* right = NULL;
if (leftSize!=0) {
left = buildCore(preorder, prebeg+1, leftSize+prebeg, inorder, inbeg, leftSize+inbeg-1);
}
if (rightSize!=0) {
right = buildCore(preorder, prebeg+leftSize+1, preend, inorder, leftSize+inbeg+1, inend);
}
root->left = left;
root->right = right;
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (preorder.empty() && inorder.empty()) {
return NULL;
}
return buildCore(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
};