-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path108.convert-sorted-array-to-binary-search-tree.cpp
More file actions
48 lines (43 loc) · 1.12 KB
/
108.convert-sorted-array-to-binary-search-tree.cpp
File metadata and controls
48 lines (43 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode id=108 lang=cpp
*
* [108] Convert Sorted Array to Binary Search Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
TreeNode *makeSortedBST(vector<int> &nums, int str, int end)
{
if(str> end){
return nullptr;
}
if (str == end)
{
TreeNode *temp = nullptr;
temp = new TreeNode(nums[str]);
return temp;
}
int mid = (str + end)/2;
TreeNode* myNode = new TreeNode(nums[mid]);
myNode->left = makeSortedBST(nums,str,mid-1);
myNode->right = makeSortedBST(nums,mid+1,end);
return myNode;
}
TreeNode *sortedArrayToBST(vector<int> &nums)
{
return makeSortedBST(nums,0,nums.size()-1);
}
};
// @lc code=end