JAVA Solution(Recursive DPS) -- 1ms


  • 0
    K
    /**
     * 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) {
            if (nums==null){
                return null;
            }
            return BST(nums,0,nums.length-1);
        }
        
        public TreeNode BST(int[] nums,int low,int high){
            if (high>=low){
                int mid = low + (high-low)/2;
                TreeNode t = new TreeNode(nums[mid]);
                t.left = BST(nums,low,mid-1);
                t.right = BST(nums,mid+1,high);
                return t;
            }else{
                return null;
            }
        }
    }

Log in to reply
 

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