把排序数组转换为高度最小的二叉搜索树
来源:互联网 发布:python写爬虫 编辑:程序博客网 时间:2024/06/08 15:21
问题:
给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。
注意事项
There may exist multiple valid solutions, return any of them.
给出数组 [1,2,3,4,5,6,7]
, 返回
4 / \ 2 6 / \ / \1 3 5 7
class Solution {
public:
/**
* @param A: A sorted (increasing order) array
* @return: A tree node
*/
TreeNode *sort(vector<int> &A,int begin,int end)
{ if(begin>end)
return NULL;
int mid=(begin+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=sort(A,begin,mid-1);
root->right=sort(A,mid+1,end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &A) {
// write your code here
if(A.size()==0)
return NULL;
int begin=0;
int end=A.size()-1;
int mid=(begin+end)/2;
TreeNode *root=new TreeNode(A[mid]);
root->left=sort(A,begin,mid-1);
root->right=sort(A,mid+1,end);
return root;}
};
思路:一开始要将数组一分为二,分别作为二叉树的左右子树。递归直至数组内无元素。
- LintCode SortedArrayToBST 把排序数组转换为高度最小的二叉搜索树
- 题目:把排序数组转换为高度最小的二叉搜索树
- lintcode-把排序数组转换为高度最小的二叉搜索树-177
- 把排序数组转换为高度最小的二叉搜索树(LintCode)
- LintCode:把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- lintCode(177)——把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- LintCode:把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- lintcode,把排序数组转换为高度最小的二叉搜索树
- LintCode | 177. 把排序数组转换为高度最小的二叉搜索树
- LintCode 把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树-LintCode
- lintcode——把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- lintcode把排序数组转换为高度最小的二叉搜索树
- 持续集成工具集之五 使用Email Extension Plugin插件
- [牛客]拼接最小字典序练习题
- 获取Jenkins project build结果
- Java和PHP在Web开发方面的八大对比
- bootstrap-suggest-plugin (bsSuggest) 联想搜索插件之——中文字符在IE下POST 时乱码现象解决方案
- 把排序数组转换为高度最小的二叉搜索树
- grails框架下修改acegi权限框架的加密方式
- Redis复制功能简述
- typedef相关
- Python函数调用“传引用”还是”传值“
- Qt下使用OpenCV2.3.1静态编译报错,解决过程记录
- 计算机基础之牛客网刷题第二篇
- For artifact {null:null:null:jar}: The groupId cannot be empty解决办法
- OV9712+3518EV200