JavaScript 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;
        var first=null,firstF=null;
        while(runner!==null)
        {
            //find first two child and link it, if cannot find assign the first next to null
            if(runner.left!==null)
            {
                if(first!==null)
                {
                    first.next=runner.left;
                    first=runner.left;
                }
                else
                {
                    if(first===null)
                        firstF=runner.left;
                    first=runner.left;
                }
            }
            if(runner.right!==null)
            {
                if(first!==null)
                {
                    first.next=runner.right;
                    first=runner.right;
                }
                else
                {
                    if(first===null)
                        firstF=runner.right;
                    first=runner.right;
                }
            }
            
            runner=runner.next;
            
        }
        connect(firstF);
    };

  • 0
    D

    Hi there, since you are using recursion in your code, how could you prove that this won't introduce more space due to the recursive function calls?


  • 1
    Y

    @danielwpz you are right, thank you for point out.


Log in to reply
 

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