My java solution


  • 0
    C
     public class Solution {
     public TreeNode sortedListToBST(ListNode head) {
        if(head == null)
            return null;
        
        int count = 0;
        
        ArrayList<Integer> nums = new ArrayList<>();
        
        while(head != null)
        {
            nums.add(head.val);
            head = head.next;
        }
        
        TreeNode node = help(nums, 0, nums.size()-1);
        return node;
    }
    
    public TreeNode help(ArrayList<Integer> nums, int start, int end)
    {
        if(start>end)
            return null;
        
        int mid = (start+end)/2;
        
        TreeNode node = new TreeNode(nums.get(mid));
        
        node.left = help(nums, start, mid-1); 
        node.right = help(nums, mid+1, end);
    
        return node;
    }
    

    }


Log in to reply
 

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