Convert Sorted Array to Binary Search Tree
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 *BST(vector<int> &num,int start,int end){
if(start>end)return NULL;
int mid=(start+end)/2;
TreeNode *head=new TreeNode(num[mid]);
head->left=BST(num,start,mid-1);
head->right=BST(num,mid+1,end);
return head;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
if(!num.size())return NULL;
return BST(num,0,num.size()-1);
}
};