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

Leetcode:Convert Sorted Array to Binary Search Tree

时间:2014-12-31 16:04:01      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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

分析:对于BST,左右子树的高度差小于等于1,则在由sorted array构建BST时把数组中间元素作为根节点,然后递归的构建左右子树。代码如下:

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

 

Leetcode:Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/Kai-Xing/p/4195759.html

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