# LeetCode – Populating Next Right Pointers in Each Node II (Java)

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Analysis

Similar to Populating Next Right Pointers in Each Node, we have 4 pointers at 2 levels of the tree. Java Solution

```public void connect(TreeLinkNode root) { if(root == null) return;   TreeLinkNode lastHead = root;//prevous level's head TreeLinkNode lastCurrent = null;//previous level's pointer TreeLinkNode currentHead = null;//currnet level's head TreeLinkNode current = null;//current level's pointer   while(lastHead!=null){ lastCurrent = lastHead;   while(lastCurrent!=null){ //left child is not null if(lastCurrent.left!=null) { if(currentHead == null){ currentHead = lastCurrent.left; current = lastCurrent.left; }else{ current.next = lastCurrent.left; current = current.next; } }   //right child is not null if(lastCurrent.right!=null){ if(currentHead == null){ currentHead = lastCurrent.right; current = lastCurrent.right; }else{ current.next = lastCurrent.right; current = current.next; } }   lastCurrent = lastCurrent.next; }   //update last head lastHead = currentHead; currentHead = null; } }```
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• Debpriya Seal

Yes. That’s the reason. Either BFS or DFS has O(n) space complexity.

• Tom Dawn

public class Solution {

if(root==null)return;

if(left != null){

left.next = right;

if(root.next!=null)right.next = root.next.left;

}

connect(root.left);

connect(root.right);

}

}

• Zheyu Jin

what’s the point of using while loop instead of recursion ?
is thi because of using constance space requirement?