美文网首页
108. Convert Sorted Array to Bin

108. Convert Sorted Array to Bin

作者: becauseyou_90cd | 来源:发表于2018-07-31 06:01 被阅读0次

    https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
    解题思路:
    用preorder traversal来解决

    代码:
    class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
    if(nums == null || nums.length == 0) return null;
    return helper(nums, 0, nums.length - 1);
    }

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

    }

    相关文章

      网友评论

          本文标题:108. Convert Sorted Array to Bin

          本文链接:https://www.haomeiwen.com/subject/vfqcvftx.html