-
Notifications
You must be signed in to change notification settings - Fork 1
/
108.cpp
34 lines (27 loc) · 875 Bytes
/
108.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
// 108. Convert Sorted Array to Binary Search Tree - https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree
#include "bits/stdc++.h"
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* createBST(vector<int>& nums, int start, int finish) {
if (start > finish) { return nullptr; }
int mid = start + (finish - start) / 2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = createBST(nums, start, mid - 1);
node->right = createBST(nums, mid + 1, finish);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return createBST(nums, 0, (int)nums.size() - 1);
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}