leetcode 108将排序数组转换为二进制搜索树

时间:2018-05-26 19:40:06

标签: java arrays recursion binary-search-tree

当我运行此leetcode问题时,我使用了以下代码:

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        TreeNode root = sortedBST(nums, 0, nums.length-1);
        return root;
    }

    public TreeNode sortedBST(int[]nums, int low, int high){
        if(low > high) return null;
        int temp = (low + high) / 2;
        TreeNode node = new TreeNode(nums[temp]);
        node.left = sortedBST(nums, 0, temp - 1);
        node.right = sortedBST(nums, temp + 1, high);
        return node;

    }
}

而不是正确的输出 对于已排序的数组[0,-3,9,-10,null,5][-10,-3,0,5,9], 我的输出结果是[0,-10,5,null,-3,-3,9,-10,null,-10,0,-3,null,null,null,null,null,-10,null,-10,0,null,-3,null,null,-10,5,-10,null,null,-3,-3,null,null,null,-10,null,-10,0,null,null,null,null,-10,null,null,-3,-10]

我对这个结果感到困惑,为什么它有这么多的输出?

1 个答案:

答案 0 :(得分:1)

更改行

    node.left = sortedBST(nums, low, temp - 1);

Mtable