Simple Recursive soln C++


#1

TreeNode *bst(vector &I,int is,int ie,vector &po,int ps,int pe){
if(is>ie||ps>pe)
return NULL;
int val=po[ps];
TreeNode *root=(TreeNode *)malloc(sizeof(TreeNode));
root->val=val;
root->left=0;
root->right=0;
int off=is;
for(;off<ie;off++)
if(I[off]==val)
break;
root->left=bst(I,is,off-1,po,ps+1,ps+off-is);
root->right=bst(I,off+1,ie,po,ps+off-is+1,pe);
return root;
}

TreeNode* Solution::buildTree(vector &A, vector &B) {
if(B.size()==0||A.size()!=B.size())
return NULL;
return bst(B,0,B.size()-1,A,0,A.size()-1);
}