题目:
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) { const int len = nums.size(); return Solution::sortedArr2BST(nums, 0, len-1); } static TreeNode* sortedArr2BST(vector<int>& nums, int begin, int end ) { if ( begin>end ) return NULL; int mid = (begin+end+1)/2; TreeNode *root = new TreeNode(nums[mid]); root->left = Solution::sortedArr2BST(nums, begin, mid-1); root->right = Solution::sortedArr2BST(nums, mid+1, end); return root; } };
tips:
利用二分查找+递归。
注意终止条件:begin>end,返回NULL。
===================================
第二次过着这道题,代码与第一次写的几乎一样。
/** * 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) { return Solution::transform(nums, 0, nums.size()-1); } static TreeNode* transform(vector<int>& nums, int begin, int end) { if ( begin>end ) return NULL; int mid = (begin+end)/2; TreeNode* root = new TreeNode(nums[mid]); root->left = Solution::transform(nums, begin, mid-1); root->right = Solution::transform(nums, mid+1, end); return root; } };