Simple Java Solution O(nlogn) 1ms


  • 0
    A
     public TreeNode sortedListToBST(ListNode head) {
            if(head==null)
                return null;
            ListNode slow = head;
            ListNode fast = head;
            ListNode endMarker = null;
            while(fast!=null && fast.next!=null){
                endMarker = slow;
                slow = slow.next;
                fast = fast.next.next;
            }
            TreeNode root = new TreeNode(slow.val);
            if(endMarker!=null) //marking end point of first list
                endMarker.next = null;
            else
                head = null;
            root.left = sortedListToBST(head);
            root.right = sortedListToBST(slow.next);
            return root;
        }

Log in to reply
 

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