题目:
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(num.size() == 0)
{
return NULL;
}
return sortedArrayToBST(num, 0, num.size()-1);
}
TreeNode *sortedArrayToBST(vector<int> &num, int begin, int end) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(begin>end)
{
return NULL;
}
else
{
int mid = begin + ((end - begin)>>1);
TreeNode* parent = new TreeNode(num[mid]);
parent->left = sortedArrayToBST(num, begin, mid-1);
parent->right = sortedArrayToBST(num, mid+1, end);
}
}
};