Populating Next Right Pointers in Each Node
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}Example
1
/ \
2 3
/ \ / \
4 5 6 7Note
Code
Last updated
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
} 1
/ \
2 3
/ \ / \
4 5 6 7Last updated
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULLpublic void connect(TreeLinkNode root) {
if (root == null) return;
if (root.left != null) {
root.left.next = root.right;
}
if (root.next != null && root.right != null) {
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
}public void connect(TreeLinkNode root) {
if (root == null) return;
TreeLinkNode start = root;
while (start != null) {
TreeLinkNode cur = start;
while (cur != null) {
if (cur.left != null) {
cur.left.next = cur.right;
}
if (cur.next != null && cur.right != null) {
cur.right.next = cur.next.left;
}
cur = cur.next;
}
start = start.left;
}
}