Convert Sorted Array to Binary Search Tree

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

 

Analyse: Using binary search to divide the sorted array into two parts, then recursively do the same process for the two parts.

Runtime: 16ms. 

Additional: IT'S THE FIRST TIME I COME UP WITH A SOLUTION WITHOUT REFERENCE. CONG!!

 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         if(nums.size() == 0) return NULL;
14         
15         return convert(nums, 0, nums.size() - 1);
16     }
17     TreeNode* convert(vector<int>& nums, int low, int high){
18         if(low > high) return NULL;
19         
20         int mid = (low + high) / 2;
21         TreeNode* root = new TreeNode(nums[mid]);
22         if(low == high) return root;
23         
24         root->left = convert(nums, low, mid - 1);
25         root->right = convert(nums, mid + 1, high);
26         
27         return root;
28     }
29     
30 };

 

posted @ 2015-07-31 10:38  amazingzoe  阅读(166)  评论(0编辑  收藏  举报