Very Very easy to understand JAVA 1MS Binary Search Solution!


  • 0
    H
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            return helper(0,nums.length-1,nums);
        }
        public TreeNode helper(int start, int end, int[] nums){
            if(start>end) return null;
            
            int mid = (start+end)/2;
            TreeNode root = new TreeNode(nums[mid]);
            TreeNode subleft = helper(start,mid-1,nums);
            TreeNode subright = helper(mid+1,end,nums);
            root.left = subleft;
            root.right = subright;
            return root;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.