-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path将有序数组转换为二叉搜索树.cpp
62 lines (53 loc) · 1.07 KB
/
将有序数组转换为二叉搜索树.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
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <utility>
#include <queue>
#include <functional>
using namespace std;
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)
{
if (nums.empty())
return nullptr;
return sortedArrayToBST(nums, 0, nums.size() - 1);
}
TreeNode* sortedArrayToBST(vector<int>& nums,int start,int end)
{
if (start > end)
return nullptr;
int mid = (start + end) >> 1;
TreeNode *head = new TreeNode(nums[mid]);
head->left = sortedArrayToBST(nums, start, mid - 1);
head->right = sortedArrayToBST(nums, mid + 1, end);
return head;
}
};
void TreeNodePrint(TreeNode *head)
{
if (head)
{
cout << head->val << endl;
TreeNodePrint(head->left);
TreeNodePrint(head->right);
}
}
int main()
{
vector<int> nums{ -10,-3,0,5,9 };
Solution a;
TreeNode *b = a.sortedArrayToBST(nums);
TreeNodePrint(b);
system("pause");
return 0;
}