1ms Java Solution

  • 0

    public class Solution {

    public TreeNode sortedListToBST(ListNode head) {
        if (head == null ) return null;
        if (head.next == null) return new TreeNode(head.val);
        ListNode slowptr = head;
        ListNode fastptr = head;
        ListNode temp= null; // this is pointer to the node which is just before middle node in the linkedlist
        while(fastptr != null && fastptr.next != null) {
            temp = slowptr;
            slowptr = slowptr.next;
            fastptr = fastptr.next.next;
        temp.next = null;
        TreeNode root = new TreeNode(slowptr.val);
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(slowptr.next);
        return root;


  • 0

    I got the totally same solution with you, but with C code, and my time is 8ms while yours is 1ms.

Log in to reply

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