leetcode 108 Convert Sorted Array to Binary Search Tree
题目连接
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
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.
/** * 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); } };
By: GadyPu 博客地址:http://www.cnblogs.com/GadyPu/ 转载请说明