Javascript solution using DFS


  • 0
    S
    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {TreeNode}
     */
    var sortedListToBST = function(head) {
        if (!head) { return null; }
        
        return helper(head, null);
    };
    
    var helper = function(head, tail) {
        if (head === tail) { return null; }
        
        let slow = head;
        let fast = head;
        while (fast !== tail && fast.next !== tail) {
            fast = fast.next.next;
            slow = slow.next;
        }
        
        let root = new TreeNode(slow.val);
        root.left = helper(head, slow);
        root.right = helper(slow.next, tail);
    
        return root; 
    };
    

Log in to reply
 

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