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

Convert Sorted Array to Binary Search Tree

时间:2014-08-17 13:02:12      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   art   div   amp   

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

思路:取数组的中点为树的根,前半部分为左子树,后半部分为右子树。

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

 

Convert Sorted Array to Binary Search Tree,布布扣,bubuko.com

Convert Sorted Array to Binary Search Tree

标签:style   blog   color   io   ar   art   div   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3917562.html

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