Created
March 13, 2019 12:14
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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