java script Recursive solution O(1) space (linked list+binary tree)


  • 0
    Y
    /**
     * Definition for binary tree with next pointer.
     * function TreeLinkNode(val) {
     *     this.val = val;
     *     this.left = this.right = this.next = null;
     * }
     */
    
    /**
     * @param {TreeLinkNode} root
     * @return {void} Do not return anything, modify tree in-place instead.
     */
    var connect = function(root) {
        if(root===null)
            return;
        var runner=root;
        while(runner!==null)
        {
            if(runner.left!==null)
            {
                runner.left.next=runner.right;
                if(runner.next!==null)
                    runner.right.next=runner.next.left;
                else
                    runner.right.next=null;
                    
                runner=runner.next;
            }
            else
            {
                return;
            }
        }
        connect(root.left);
    };

Log in to reply
 

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