-
Notifications
You must be signed in to change notification settings - Fork 257
/
convert-sorted-array-to-binary-search-tree-with-minimal-height.cpp
59 lines (52 loc) · 1.54 KB
/
convert-sorted-array-to-binary-search-tree-with-minimal-height.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Time: O(n)
// Space: O(logn)
/**
* 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: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode *sortedArrayToBST(vector<int> &A) {
return sortedArrayToBSTHelper(A, 0, A.size() - 1);
}
TreeNode *sortedArrayToBSTHelper(vector<int> &A, int start, int end) {
if (start <= end) {
TreeNode *node = new TreeNode(A[start + (end - start) / 2]);
node->left = sortedArrayToBSTHelper(A, start, start + (end - start) / 2 - 1);
node->right = sortedArrayToBSTHelper(A, start + (end - start) / 2 + 1, end);
return node;
}
return nullptr;
}
};
class Solution2 {
public:
/**
* @param A: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode *sortedArrayToBST(vector<int> &A) {
return sortedArrayToBSTHelper(A, 0, A.size());
}
TreeNode *sortedArrayToBSTHelper(vector<int> &A, int start, int end) {
if (start < end) {
TreeNode *node = new TreeNode(A[start + (end - start) / 2]);
node->left = sortedArrayToBSTHelper(A, start, start + (end - start) / 2);
node->right = sortedArrayToBSTHelper(A, start + (end - start) / 2 + 1, end);
return node;
}
return nullptr;
}
};