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

来源:互联网 发布:武汉网络诈骗最新消息 编辑:程序博客网 时间:2024/04/30 23:39

题目描述:

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;    }}


0 0