Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
以序列的中间元素作为根,转换后的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) { return sortedArrayToBSTHelp(nums, 0, nums.size()); } TreeNode* sortedArrayToBSTHelp(vector<int>& nums, int l, int r){ if(l >= r) return NULL; int mid = (l + r) >> 1; TreeNode* root = new TreeNode(nums[mid]); root->left = sortedArrayToBSTHelp(nums, l, mid); root->right = sortedArrayToBSTHelp(nums, mid + 1, r); return root; }};新闻热点
疑难解答