leetcode 108 Convert Sorted Array to Binary Search Tree
原题链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Description
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Solution
/**
* 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) {
int n = 0;
if(!(n = nums.size())) return nullptr;
nums.insert(nums.begin(), 0);
function<TreeNode*(int , int)> built = [&](int l, int r)->TreeNode* {
if(l > r) return nullptr;
int m = (l + r) >> 1;
TreeNode *x = new TreeNode(nums[m]);
x->left = built(l, m - 1);
x->right = built(m + 1, r);
return x;
};
return built(1, n);
}
};