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

[Leetcode]Convert Sorted Array to Binary Search Tree

时间:2015-03-15 23:32:20      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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

分治是比较好而且容易想到的思路。

 1 class Solution {
 2 public:
 3     TreeNode *mergeAToT(vector<int> &num,int left,int right){
 4         if(left>right)
 5             return NULL;
 6         int mid = (right+left)/2;
 7         TreeNode *node = new TreeNode(num[mid]);
 8         node->left = mergeAToT(num,left,mid-1);
 9         node->right = mergeAToT(num,mid+1,right);
10         return node;
11     }
12     TreeNode *sortedArrayToBST(vector<int> &num) {
13         return mergeAToT(num,0,num.size()-1);
14     }
15 };

 

[Leetcode]Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/desp/p/4340748.html

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