Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lctseng/5976b94d8f997ebba501146ebc0597af to your computer and use it in GitHub Desktop.
Save lctseng/5976b94d8f997ebba501146ebc0597af to your computer and use it in GitHub Desktop.
class Solution {
public:
TreeNode* bstFromPreorder(vector<int>& preorder, int& index, int parentIndex) {
if(index >= preorder.size() || (parentIndex >= 0 && preorder[index] >= preorder[parentIndex])){
return nullptr;
}
else{
TreeNode* root = new TreeNode(preorder[index]);
int thisIndex = index;
index++;
root->left = bstFromPreorder(preorder, index, thisIndex);
root->right = bstFromPreorder(preorder, index, parentIndex);
return root;
}
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
int index = 0;
return bstFromPreorder(preorder, index, -1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment