0

When I run this leetcode problem, I used the code below:

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;

    }
}

instead of the correct output [0,-3,9,-10,null,5] for the sorted array [-10,-3,0,5,9], my output result is [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].

I'm confused about this results, why it has so many outputs?

1 Answer 1

1

Change the line

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

To

    node.left = sortedBST(nums, low, temp - 1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.