Easy java solution with comments


  • 0
    D

    /**

    • 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) {

       int low=0;
       int high=nums.length-1;
       
       return formTree(nums,low,high);
      

      }

      public TreeNode formTree(int[] nums, int low, int high)
      {
      //Base case: if low is greater than high, return null
      if(low>high)
      return null;

       //General case: 
       //find mid element
       int mid=(low+high)/2;
        
       //form the root node   
       TreeNode root=new TreeNode(nums[mid]);
         
       //recurse on left and right subtrees  
       root.left=formTree(nums,low,mid-1);
           
       root.right=formTree(nums,mid+1,high);
         
       //return root  
       return root;    
      

      }
      }


Log in to reply
 

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