Why my Java solution is not working ?


  • 0
    W

    My idea is once I have the next node of root, I can set the next node for its left and right leaf. So I use recursion to handle it. But it failed on below case :

    Output:
    {1,#,2,3,#,4,5,6,#,7,#}
    Expected:
    {1,#,2,3,#,4,5,6,#,7,8,#}

    public class Solution {
    public void connect(TreeLinkNode root) {
    if (root == null) return;

        if (root.left != null) {
            root.left.next = root.right;
        }
        
        if (root.next != null) {
            TreeLinkNode next = root.next.left != null ? root.next.left : root.next.right;
            
            if (root.right != null) {
                root.right.next = next;
            } else if (root.left != null) {
                root.left.next = next;
            }
        }
        
        connect(root.left);
        connect(root.right);
    }
    

    }


Log in to reply
 

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