Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:
1. 找到数组的中间节点将其置为根节点
2. 左边的即为左子树
3. 右边的即为右子树
4. 递归求解
/** * 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* sortBST(vector<int>& nums, int begin, int end){ if(begin > end) return 0; int rootIndex = begin+(end-begin)/2; //更简单的应该是 (begin+end)/2 TreeNode* root = new TreeNode(nums[rootIndex]); root->left = sortBST(nums, begin, rootIndex-1); root->right = sortBST(nums, rootIndex+1, end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { return sortBST(nums, 0, nums.size()-1); } };