Skip to content

Instantly share code, notes, and snippets.

@sauravgpt
Created May 27, 2021 03:28
Show Gist options
  • Save sauravgpt/9e4de989a49a9a601dd3405c745e1c2f to your computer and use it in GitHub Desktop.
Save sauravgpt/9e4de989a49a9a601dd3405c745e1c2f to your computer and use it in GitHub Desktop.
Contruct BST from Preorder Traversal O(n^2)
int findIndex(vector<int>& pre, int l, int r, int v) {
while (l <= r) {
if (pre[l] > v) return l;
l++;
}
return -1;
}
TreeNode* buildTree(vector<int>& pre, int s, int e) {
if (s > e) return nullptr;
TreeNode* root = new TreeNode(pre[s]);
int rightIndex = findIndex(pre, s + 1, e, root->val);
if (rightIndex != -1) {
root->left = buildTree(pre, s + 1, rightIndex - 1);
root->right = buildTree(pre, rightIndex, e);
}
else {
root->left = buildTree(pre, s + 1, e);
}
return root;
}
int main() {
vector<int> pre = { 10, 5, 1, 7, 40, 50 };
TreeNode* root = buildTree(pre, 0, pre.size() - 1);
levelOrderTraversal(root);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment