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

【leetcode】Convert Sorted Array to Binary Search Tree

时间:2015-04-19 21:10:54      阅读:173      评论: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 *createTree(vector<int> &num,int begin,int end)
 4     {
 5         if(begin>end) return NULL;
 6         int mid=(begin+end)/2;
 7         TreeNode *root=new TreeNode(num[mid]);
 8         root->left=createTree(num,begin,mid-1);
 9         root->right=createTree(num,mid+1,end);
10         return root;
11     }
12 
13     TreeNode *sortedArrayToBST(vector<int> &num) {
14         if(num.size()==0) return NULL;
15         return createTree(num,0,num.size()-1);
16     }
17 };

 

【leetcode】Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4439800.html

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