码迷,mamicode.com
首页 > 其他好文 > 详细

Convert Sorted Array to Binary Search Tree

时间:2015-07-31 12:19:02      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4691506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!