-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path177.h
46 lines (41 loc) · 1.17 KB
/
177.h
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
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param A: an integer array
* @return: A tree node
*/
TreeNode * sortedArrayToBST(vector<int> &A) {
// write your code here
//return sortedArrayToBST(A, 0, A.size());
return sortedArrayToBST(A, 0, A.size()-1);
}
// leetcode可以通过
// TreeNode *sortedArrayToBST(vector<int> &A, int l, int r){
// if(l >= r ) return nullptr;
// int mid = l + (r-l)/2;
// TreeNode *root = new TreeNode(A[mid]);
// root->left = sortedArrayToBST(A, l, mid);
// root->right= sortedArrayToBST(A, mid+1, r);
// return root;
// }
TreeNode *sortedArrayToBST(vector<int> &A, int l, int r){
if(l > r ) return nullptr;
int mid = l + (r-l)/2;
TreeNode *root = new TreeNode(A[mid]);
root->left = sortedArrayToBST(A, l, mid-1);
root->right= sortedArrayToBST(A, mid+1, r);
return root;
}
};