Why my solution cannot pass? Can anyone kindly help?


  • 0
    F
    public void connect(TreeLinkNode root) {
        if(root == null){
            return;
        }
        
        if(root.left != null){
            if(root.right != null){
                root.left.next = root.right;
            } else if(root.next != null){
                root.left.next = setNextNode(root.next);
            }
        }
            
        if(root.right != null){
            if(root.next != null){
                root.right.next = setNextNode(root.next);
            }
        }
        connect(root.left);
        connect(root.right);
    }
    
    private TreeLinkNode setNextNode(TreeLinkNode tempNode){
        while(tempNode != null){
            if(tempNode.left != null || tempNode.right != null){
                return tempNode.left != null ? tempNode.left : tempNode.right;
            }
            tempNode = tempNode.next;
        }
        return null;
    }

  • 0
    D

    It seems problem is here
    connect(root.left);
    connect(root.right);

    try switch order of calls


Log in to reply
 

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