首页 > 其他 > 详细

[Leetcode]Convert Sorted Array to Binary Search Tree

时间:2015-03-15 23:30:15      阅读:348      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!