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 fpdjsns/74392ef8dd5380de77c8e8e60babe02b to your computer and use it in GitHub Desktop.
Save fpdjsns/74392ef8dd5380de77c8e8e60babe02b to your computer and use it in GitHub Desktop.
[leetcode] 1008. Construct Binary Search Tree from Preorder Traversal : https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* makeTree(TreeNode* root, int val){
if(root == NULL) return new TreeNode(val);
if(root->val > val) root->left = makeTree(root->left, val);
else root->right = makeTree(root->right, val);
return root;
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
TreeNode* root = NULL;
for(int i=0;i<preorder.size();i++)
root = makeTree(root, preorder[i]);
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment