Skip to content

Commit 1e2fed5

Browse files
committed
108. Convert Sorted Array to Binary Search Tree
1 parent 1aa9612 commit 1e2fed5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//Runtime: 13 ms
2+
class Solution {
3+
public:
4+
5+
TreeNode* insert(TreeNode* root,int data)
6+
{
7+
if(!root)
8+
return new TreeNode(data);
9+
else if(root->val < data)
10+
return root->right = insert(root->right, data);
11+
else
12+
return root->left = insert(root->left, data);
13+
}
14+
15+
TreeNode* MakeBST(TreeNode* root, int l, int h, vector<int> &nums)
16+
{
17+
if(l>h)
18+
return NULL;
19+
20+
int mid = (l+h)/2;
21+
root = insert(root, nums[mid]);
22+
23+
root->right = MakeBST(root, mid+1, h, nums);
24+
root->left = MakeBST(root, l,mid-1, nums);
25+
26+
return root;
27+
}
28+
29+
TreeNode* sortedArrayToBST(vector<int>& nums) {
30+
return MakeBST(NULL, 0, nums.size()-1, nums);
31+
}
32+
};

0 commit comments

Comments
 (0)