LintCode:177. 把排序数组转换为高度最小的二叉搜索树
2018-03-28 16:28
393 查看
题目:
![](https://img-blog.csdn.net/2018032816252961?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI3MTM5MTU1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
思路:直接采用中间值来作为二叉树的根节点;将原数组分成左右均等或者相差一个数的两个新数组;然后递归的对这两个新数组进行相同的处理,这样对于每一个根节点,其左右子树的高度相差绝对值不会超过1,也就是满足了二叉平衡树的要求了。/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param A: an integer array
* @return: A tree node
*/
public TreeNode sortedArrayToBST(int[] A) {
// write your code here
if(A==null||A.length==0) return null;
int begin=0;int end=A.length-1;
int mid=(begin+end)/2;
TreeNode pRoot=new TreeNode(A[mid]);
pRoot.left=sortedArrayToBSTCore(A,begin,mid-1);
pRoot.right=sortedArrayToBSTCore(A,mid+1,end);
return pRoot;
}
public TreeNode sortedArrayToBSTCore(int[] A,int begin,int end){
if(begin>end){
return null;
}
int mid=(begin+end)/2;
TreeNode treeNode=new TreeNode(A[mid]);
treeNode.left=sortedArrayToBSTCore(A,begin,mid-1);
treeNode.right=sortedArrayToBSTCore(A,mid+1,end);
return treeNode;
}
}
思路:直接采用中间值来作为二叉树的根节点;将原数组分成左右均等或者相差一个数的两个新数组;然后递归的对这两个新数组进行相同的处理,这样对于每一个根节点,其左右子树的高度相差绝对值不会超过1,也就是满足了二叉平衡树的要求了。/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param A: an integer array
* @return: A tree node
*/
public TreeNode sortedArrayToBST(int[] A) {
// write your code here
if(A==null||A.length==0) return null;
int begin=0;int end=A.length-1;
int mid=(begin+end)/2;
TreeNode pRoot=new TreeNode(A[mid]);
pRoot.left=sortedArrayToBSTCore(A,begin,mid-1);
pRoot.right=sortedArrayToBSTCore(A,mid+1,end);
return pRoot;
}
public TreeNode sortedArrayToBSTCore(int[] A,int begin,int end){
if(begin>end){
return null;
}
int mid=(begin+end)/2;
TreeNode treeNode=new TreeNode(A[mid]);
treeNode.left=sortedArrayToBSTCore(A,begin,mid-1);
treeNode.right=sortedArrayToBSTCore(A,mid+1,end);
return treeNode;
}
}
相关文章推荐
- 【LintCode 简单】177. 把排序数组转换为高度最小的二叉搜索树
- python_lintcode_177. 把排序数组转换为高度最小的二叉搜索树_156. 合并区间
- LintCode | 177. 把排序数组转换为高度最小的二叉搜索树
- LintCode-把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树-LintCode
- lintcode 把排序数组转换为高度最小的二叉搜索树
- LintCode 177-把排序数组转换为高度最小的二叉搜索树
- lintcode-177-把排序数组转换为高度最小的二叉搜索树
- LintCode 把排序数组转换为高度最小的二叉搜索树
- [LintCode 177] 把排序数组转换为高度最小的二叉搜索树(Python)
- Lintcode-递归-177 把排序数组转换为高度最小的二叉搜索树
- lintcode,把排序数组转换为高度最小的二叉搜索树
- LintCode 把排序数组转换为高度最小的二叉搜索树
- LintCode:把排序数组转换为高度最小的二叉搜索树
- lintcode把排序数组转换为高度最小的二叉搜索树
- Lintcode 177.把排序数组转换为高度最小的二叉搜索树
- lintcode-把排序数组转换为高度最小的二叉搜索树-177
- LintCode:把排序数组转换为高度最小的二叉搜索树
- lintCode(177)——把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树-LintCode