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

108. Convert Sorted Array to Bin

作者: 苏州城外无故人 | 来源:发表于2019-03-05 13:00 被阅读0次
    image.png

    思路:递归,二分查找
    要把一个数组变为二分查找树,数组中间点就是根节点,依次递归构造左右子树。


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

    相关文章

      网友评论

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

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