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 *getBST(vector<int> &num,int start,int end) { if(start>end)return NULL; int mid = (start + end)>>1; TreeNode *root = new TreeNode(num[mid]); root->left = getBST(num,start,mid-1); root->right = getBST(num,mid+1,end); return root; } TreeNode *sortedArrayToBST(vector<int> &num) { if(num.size()==0)return NULL; else return getBST(num,0,num.size()-1);//attention here }};