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* ArrayToBst(vector<int>& nums, int start, int end) { if (start == end) return NULL; int mid = (start + end) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = ArrayToBst(nums, start, mid);//左右子树直接递归 root->right = ArrayToBst(nums, mid+1, end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { return ArrayToBst(nums, 0, nums.size()); } };