题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:要建立平衡二叉查找树,只需要采用二分法,将每段数组的中间节点的值存入树节点即可,中间节点左右两段的数组的中间结点又作为该树节点的左右子树节点。
代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.empty())return NULL;
if(num.size()==1)return new TreeNode(num[0]);
int high=num.size()-1;
int low=0,mid;
TreeNode *root=new TreeNode(0);
if(high>=low){
mid=(low+high)/2;
root->val=num[mid];
vector<int> left;
if(mid>0)left.assign(num.begin(),num.begin()+mid);
vector<int> right(num.begin()+mid+1,num.end());
root->left=sortedArrayToBST(left);
root->right=sortedArrayToBST(right);
}
return root;
}
};