My O(1) space recursive solution


  • -1
    P
    public void connect(TreeLinkNode root) {
        if(root == null) return;
        TreeLinkNode child = root.right;
        if(root.right == null) child = root.left;
        if(root.left != null) {
            root.left.next = root.right;
        }
            
        if(child != null) {
            TreeLinkNode next = root.next;
            while(next != null) {
                if(next.left != null) {
                    child.next = next.left;
                    break;
                }
                else if(next.right != null) {
                    child.next = next.right;
                    break;
                }
                else next = next.next;
            }
        }
        connect(root.right);
        connect(root.left);
    }

Log in to reply
 

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