sortedListToBST with JavaScript


  • 0
    N
    /**
     * 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;
        }
        
        let node = head;
        let input = [];
        
        while(node) {
            input.push(node.val);
            node = node.next;
        }
        input = input.sort( (a, b) => a - b);
        
        const recursion = (arr, low, high) => {
            if(low > high) {
                return null;
            }
            
            let mid = Math.ceil((low + high) / 2);
            let bst = new TreeNode(arr[mid]);
            
            bst.left = recursion(arr, low, mid - 1);
            bst.right = recursion(arr, mid + 1, high);
            
            return bst;
        }
        
        return recursion(input, 0, input.length - 1);
    };
    

Log in to reply
 

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