# Populating Next Right Pointers in Each Node II solution with comments

• ``````/**
* Definition for binary tree with next pointer.
*     int val;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
if(root==null)
return;
root.next=null;
setpoint(root);

}
{
//return if node is null or node has no children
if(node==null || (node.right==null && node.left==null))
{
return;
}
//right node is null
if(t.right==null)
{
//traverse linked-list of parent to find first node with at least one children
t=t.next;
while(t!=null && (t.right==null && t.left==null)  )
{
t=t.next;
}
if(t==null)
{
node.left.next=null;
}
else
{
if(t.left!=null)
node.left.next=t.left;
else
node.left.next=t.right;
}

setpoint(node.left);

}
else
{
if(node.left!=null)
{
node.left.next=node.right;

}
//traverse linked-list of parent to find first node with at least one children
t=t.next;
while( t!=null && ( t.right==null && t.left==null)  )
{
t=t.next;

}

if(t==null )
{
node.right.next=null;
}
else
{
if(t.left!=null)
node.right.next=t.left;
else
node.right.next=t.right;
}
//recursively solve for right subtree
setpoint(node.right);
////recursively solve for left subtree
setpoint(node.left);
}
}
}
``````

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