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?


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) 
    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
        lastCurrent = lastHead;
            //left child is not null
            if(lastCurrent.left!=null)    {
                if(currentHead == null){
                    currentHead = lastCurrent.left;
                    current = lastCurrent.left;
                    current.next = lastCurrent.left;
                    current = current.next;
            //right child is not null
                if(currentHead == null){
                    currentHead = lastCurrent.right;
                    current = lastCurrent.right;
                    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:
String foo = "bar";

  1. Zheyu Jin on 2015-6-29

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

  2. Tom Dawn on 2016-1-25

    public class Solution {

    public void connect(TreeLinkNode root) {


    TreeLinkNode left=root.left;

    TreeLinkNode right=root.right;

    if(left != null){

    left.next = right;

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






  3. Debpriya Seal on 2016-3-7

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

Leave a comment