力扣 | 108. 将有序数组转换为二叉搜索树

力扣 | 108. 将有序数组转换为二叉搜索树_第1张图片

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Problem_108_SortedArrarToBST {
    public TreeNode sortedArrayToBST(int [] nums){

        return buildBST(nums,0,nums.length - 1);
    }
    public TreeNode buildBST(int [] nums,int left,int right){
        if(left > right) return null;
        int mid = left + (right - left)/2;//为了数组不越界
        TreeNode root = new TreeNode(nums[mid]);
        root.left = buildBST(nums,left,mid - 1);
        root.right = buildBST(nums,mid + 1,right);
        return root;
    }
}

你可能感兴趣的:(算法,数据结构,java)