-
Notifications
You must be signed in to change notification settings - Fork 0
/
108.将有序数组转换为二叉搜索树.cpp
46 lines (41 loc) · 1.13 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
/*
* @lc app=leetcode.cn id=108 lang=cpp
*
* [108] 将有序数组转换为二叉搜索树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include<vector>
using namespace std;
class Solution {
public:
TreeNode* toBst(vector<int>& nums, int begin, int end)
{
int size = end - begin;
TreeNode* curr = nullptr;
if(size == 0) return curr;
else if(size == 1) curr = new TreeNode(nums[begin]);
else
{
int currIndex = begin + size / 2;
curr = new TreeNode(nums[currIndex]);
curr->left = toBst(nums, begin, currIndex);
curr->right = toBst(nums, currIndex + 1, end);
}
return curr;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return toBst(nums, 0, nums.size());
}
};
// @lc code=end