JavaScript solution


  • 1
    L
    function sortedListToBST(head) {
        if (!head) {
            return null;
        }
        
        if (!head.next) {
            return new TreeNode(head.val);
        }
        
        var m = head;
        var prev = head;
        var tail = head;
        
        // head, prev, m -> ... -> null
        while (tail && tail.next) {
            tail = tail.next.next;
            prev = m;
            m = m.next;
        }
        // head -> ... -> prev -> m -> ... -> null
        
        prev.next = null;
        
        var n = new TreeNode(m.val);
        n.left = sortedListToBST(head);
        n.right = sortedListToBST(m.next);
        return n;
    }

  • 0
    R
    This post is deleted!

Log in to reply
 

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