# O(1) space complexity, O(n) time complexity solution with comments and explanation

• The idea is to have a pointer to the previous level so we can build the linkedlist for current level. See code below, has lots of comments for explanation.
Solution runs in 1ms if I remove all the comments

``````public void connect(TreeLinkNode root) {
if (root == null) return;
if (root.left != null) { root.left.next = root; root.right.next = root; }

/**
* 1) If current is a left child, set curr.next to right child
* 2) If current is a right child, set curr.next to parent.next.left child
* 3) Set the childs next pointer to parent
* 4) If curr == null, go to next level and continue with (1)
*/
while (curr != null) {

if (parent.right == curr) {
//curr is a right child, so set to parent.next.left
if (parent.next != null) curr.next = parent.next.left;
else curr.next = null;
} else {
//curr is a left child, so set to parent.right
curr.next = parent.right;
}

//set child's next pointer to curr
if (curr.left != null) { curr.left.next = curr; curr.right.next = curr; }