forked from arkingc/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
108.cpp
29 lines (27 loc) · 758 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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int l = 0,r = nums.size() - 1;
return sortedArrayToBSTCore(nums,l,r);
}
public:
TreeNode* sortedArrayToBSTCore(vector<int> &nums,int l,int r){
if(l > r) return NULL;
int mid = (l + r) >> 1;
TreeNode *root = new TreeNode(nums[mid]);
if(l < r){
root->left = sortedArrayToBSTCore(nums,l,mid - 1);
root->right = sortedArrayToBSTCore(nums,mid + 1,r);
}
return root;
}
};