Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
二分递归转换
1 /** 2 * Definition for binary tree 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 public: 12 TreeNode *createTree(vector<int> &num, int left, int right) 13 { 14 if (left > right) 15 return NULL; 16 17 int mid = (left + right) / 2; 18 19 TreeNode *leftNode = createTree(num, left, mid - 1); 20 TreeNode *rightNode = createTree(num, mid + 1, right); 21 22 TreeNode *node = new TreeNode(num[mid]); 23 24 node->left = leftNode; 25 node->right = rightNode; 26 27 return node; 28 } 29 30 TreeNode *sortedArrayToBST(vector<int> &num) { 31 // Start typing your C/C++ solution below 32 // DO NOT write int main() function 33 return createTree(num, 0, num.size() - 1); 34 } 35 };