forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
49 lines (37 loc) · 1.02 KB
/
main.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
/// Source : https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
/// Author : liuyubobobo
/// Time : 2018-10-30
#include <iostream>
#include <vector>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Recursion
/// Time Complexity: O(n)
/// Space Complexity: O(logn)
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size() == 0)
return NULL;
return buildTree(nums, 0, nums.size() - 1);
}
private:
TreeNode* buildTree(const vector<int>& nums, int l, int r){
if(l > r) return NULL;
if(l == r) return new TreeNode(nums[l]);
int mid = (l + r) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = buildTree(nums, l, mid - 1);
root->right = buildTree(nums, mid + 1, r);
return root;
}
};
int main() {
return 0;
}