-
Notifications
You must be signed in to change notification settings - Fork 0
/
convertsortedarray.cpp
42 lines (35 loc) · 954 Bytes
/
convertsortedarray.cpp
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> array;
TreeNode * test(int begin, int end){
TreeNode * root = new TreeNode(0);
int mid = (begin+end)/2;
root->val = array[mid];
if(mid - 1 >= begin){
root->left = test(begin,mid-1);
}
if(mid + 1 <= end){
root->right = test(mid+1,end);
}
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
array = num;
TreeNode * root = NULL;
if(num.size() == 0)
return root;
root = test(0,num.size()-1);
return root;
}
};