题目:
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* BuildTree(vector<int> &num, int start, int end) { 13 if (start == end) { 14 return NULL; 15 } 16 int middle = start + (end - start) / 2; 17 TreeNode* root = new TreeNode(num[middle]); 18 TreeNode* left_child = BuildTree(num, start, middle); 19 TreeNode* right_child = BuildTree(num, middle + 1, end); 20 root->left = left_child; 21 root->right = right_child; 22 return root; 23 } 24 TreeNode *sortedArrayToBST(vector<int> &num) { 25 return BuildTree(num, 0, num.size()); 26 } 27 };