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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
return build(num,0,num.size()-1);
}
TreeNode *build(vector<int> &num, int start, int end) {
if(start > end) return NULL;
if(start == end) return new TreeNode(num[start]);
int middle = start+(end-start)/2;
TreeNode *root = new TreeNode(num[middle]);
root->left = build(num,start,middle-1);
root->right = build(num,middle+1,end);
}
};