108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / 
   -3   9
   /   /
 -10  5


用一个已排序的数组构建一个平衡二叉搜索树

C++(16ms):
 1 /**
 2  * Definition for a binary tree node.
 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* sortedArrayToBST(vector<int>& nums) {
13         int len = nums.size() ;
14         if (len == 0)
15             return NULL ;
16         if (len == 1)
17             return new TreeNode(nums[0]) ;
18         int mid = len/2 ;
19         TreeNode* root = new TreeNode(nums[mid]) ;
20         vector<int> leftArr(nums.begin() , nums.begin()+mid ) ;
21         vector<int> rightArr(nums.begin()+mid+1 , nums.end() ) ;
22         root->left = sortedArrayToBST(leftArr) ;
23         root->right = sortedArrayToBST(rightArr) ;
24         return root ;
25     }
26 };
 
原文地址:https://www.cnblogs.com/mengchunchen/p/8575506.html