Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
6 / \ 3 2 / \ / \ 1 4 7 8 After calling your function, the tree should look like: 6 -> NULL / \ 3 -> 2 -> NULL / \ / \ 1-> 4->7-> 8 -> NULL
public class RightPointer {
public void connect(TreeLinkNode root) {
if(root == null)
return;
if(root.left != null){
root.left.next = root.right;
if(root.next != null)
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode next;
TreeNode(int x) {
val = x;
}
}
}