数组——将排序数组转换为平衡二叉搜索树

题目描述:

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

和有序链表化为BST方法一样,递归求解; 注:中间必须要两个中间结点的后一个!

public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        if(num == null||num.length == 0)
            return null;
        return helper(num,0,num.length-1);
    }
    public TreeNode helper(int []num,int low ,int high)
        {
        if(low>high)
            return null;
        int center=low+(high-low)/2;
        //若数组元素个数为偶数,则中间结点选取两个中的后一个。
        if((high-low)%2==1)
            center++;
        TreeNode node=new TreeNode(num[center]);
        node.left=helper(num,low,center-1);
        node.right=helper(num,center+1,high);
        return node;
    }
}
    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/jingsuwen1/article/details/51427833
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞