题目
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析
给定一个有序序列,构造一颗平衡的二叉查找树。
思想:序列中值构造根节点,递归,前半序列构造左子树,有伴序列构造右子树。
AC代码
/**
* 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.empty())
return NULL;
else
return make(nums.begin(), nums.end());
}
template <typename Iter>
TreeNode *make(Iter beg, Iter end)
{
if (beg == end)
return NULL;
//求元素节点个数
int size = end - beg;
TreeNode *root = new TreeNode(*(beg + size / 2));
root->left = make(beg, beg + size / 2);
root->right = make(beg + size / 2 + 1, end);
return root;
}
};