题解 | #将升序数组转化为平衡二叉搜索树#

将升序数组转化为平衡二叉搜索树

http://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */
public class Solution {
    /**
     * 
     * @param num int整型一维数组 
     * @return TreeNode类
     */
    public TreeNode F (int[] num,int left,int right) {
        
        if(left>right) return null;
        int mid = (int) Math.round((right+left*1.0)/2); //特意把里面的变成double型
        int val = num[mid];
        TreeNode root = new TreeNode(val);
         if(left==right) return root;
        root.left = F(num,left,mid-1);
        root.right = F(num,mid+1,right);
        return root;
        
    }
    public TreeNode sortedArrayToBST (int[] num) {
        // write code here
        if(num.length<=0) return null;
        return F(num,0,num.length-1);
        
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务