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

LeetCode Convert Sorted Array to Binary Search Tree

时间:2014-12-29 22:55:25      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:

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

解题思路:根据递增序列,求平衡二叉查找树,根据平衡二叉查找树的性质,其左右都是二叉查找树,用递归可以比较轻松求解。但要注意边界问题及下标的起始位置。

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *getBST(vector<int> &num,int start,int end)
{
if(start>end)return NULL;
int mid = (start + end)>>1;
TreeNode *root = new TreeNode(num[mid]);
root->left = getBST(num,start,mid-1);
root->right = getBST(num,mid+1,end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
if(num.size()==0)return NULL;
else return getBST(num,0,num.size()-1);//attention here
}
};

LeetCode Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/55open/p/4192499.html

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