LeetCode108 Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. (Medium)
分析:
因为要构成BBST,所以要从中点开始,左边为左子树,右边为右子树,采用helper函数传递初始结束两个参数,递归求解即可。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 private: 12 TreeNode* helper(vector<int>& nums, int start, int end) { 13 if (start >= end) { 14 return nullptr; 15 } 16 int mid = start + (end - start) / 2; 17 TreeNode* root = new TreeNode(nums[mid]); 18 root -> left = helper(nums, start, mid); 19 root -> right = helper(nums, mid + 1, end); 20 return root; 21 } 22 public: 23 TreeNode* sortedArrayToBST(vector<int>& nums) { 24 TreeNode* result = helper(nums, 0, nums.size()); 25 return result; 26 } 27 };