【问题标题】:leetcode 108 Convert Sorted Array to Binary Search Treeleetcode 108 将排序数组转换为二叉搜索树
【发布时间】:2018-11-05 20:52:30
【问题描述】:

当我运行这个 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]

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

【问题讨论】:

    标签: java arrays recursion binary-search-tree


    【解决方案1】:

    换行

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多