链接:LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:
### 解题思路
1.每次随机一个要插入的数字(避免搜索树过度不平衡)
2.插入过的数字,就不在插入了
3.调用Insert1函数进行插入二叉搜索树
- - -
### 题解代码
```
[[cpp]]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param nums: the sorted array
* @return: the root of the tree
*/
TreeNode* Insert1(TreeNode* root, int node) {
if (!root) {
TreeNode* res = new TreeNode(node);
return res;
}
TreeNode* cur = root;
while (cur) {
if (node >= cur->val) {
if (!cur->right) {
cur->right = new TreeNode(node);
break;
}
cur = cur->right;
} else {
if (!cur->left) {
cur->left = new TreeNode(node);
break;
}
cur = cur->left;
}
}
return root;
}
TreeNode* convertSortedArraytoBinarySearchTree(vector<int> &nums) {
// Write your code here.
int len = nums.size();
if (len <= 0) {
return nullptr;
}
std::unordered_set<int> visited;
TreeNode* root = nullptr; // 注意,这里必须写初始化!!!!!!!!
while (visited.size() < nums.size()) {
int index = random() % nums.size();
if (visited.find(index) != visited.end()) {
continue;
}
visited.insert(index);
root = Insert1(root, nums[index]); //不断把数组中的节点,插入到树当中
}
return root;
}
};
```