Recursive Java Solution for converting Sorted array into BST <Easy to understand>


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

Log in to reply
 

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