[LeetCode]108. Convert Sorted Array to Binary Search Tree
题目描述
思路
DFS
对于已经排好序的数组,构建二叉搜索树的时候可以按照索引构造,每次从当前序列的中点开始构造
代码
#include <iostream>
#include <vector>
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) {
return insert(nums, 0, nums.size());
}
TreeNode* insert(vector<int>& nums, int start, int end) {
if (start >= end)
return NULL;
int cur = (end + start) >> 1;
TreeNode* root = new TreeNode(nums[cur]);
root->left = insert(nums, start, cur);
root->right = insert(nums, cur + 1, end);
return root;
}
void visit(TreeNode* root) {
if (root == NULL)
return;
if (root->left) {
visit(root->left);
}
cout << root->val << " ";
if (root->right) {
visit(root->right);
}
}
};
int main() {
vector<int> nums = { 1, 2, 3,4,5 };
Solution s;
s.visit(s.sortedArrayToBST(nums));
cout << endl;
system("pause");
return 0;
}
1491



被折叠的 条评论
为什么被折叠?



