二分法建立二叉树,每次把左半部分作为左子树右半部分作为右子树,递归建立BST。
#include<bits/stdc++.h>
using namespace std;
/**
* 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 {
private:
void makeBST(TreeNode* &root, vector<int>& nums, int m, int n)//以root为根节点用nums数组中从m,到n序列二分建立二叉树
{
if (m>n)
{
return;
}
int t = (m + n) / 2;
if (root == NULL)
{
root = new TreeNode(nums[t]);
root->left = NULL;
root->right = NULL;
makeBST(root->left, nums, m, t - 1);
makeBST(root->right, nums, t + 1, n);
}
return;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int n;
n = nums.size();
if (n == 0)
return NULL;
sort(nums.begin(), nums.end());
TreeNode* root=NULL;
makeBST(root, nums, 0, n - 1);
return root;
}
};