Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
思路
BST是所有左节点小于当前节点,所有右节点大于当前节点,且子树的度之间差不得大于1.
数组已经排好序,那么就每次选一个mid点开始创建,递归的二分。
/**
* 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 {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0)return NULL;
return bin(nums,0,nums.size()-1);
}
TreeNode* bin(vector<int>&nums,int low,int high){
if(low>high){
return NULL;
}
int mid = (low+high)/2;
//cout<<nums[mid]<<endl;
TreeNode *p = new TreeNode(nums[mid]);
p->left=bin(nums,low,mid-1);
p->right= bin(nums,mid+1,high);
return p;
}
};