Populating Next Right Pointers in Each Node II
Question
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
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.
Note:
You may only use constant extra space.
For example, Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
Analysis
For that you can only use constant space to add the next pointer, the intuitive approach of using a queue to track node level by level is not applicable. Here we have to notice a critical point that each level of nodes are already linked if we can add the next pointer before we access the nodes on that level.
So we can use two pointers, one tracking the head node of next Level and the other the pre-Node.
Solution
public void connect(TreeLinkNode root) {
TreeLinkNode dummyHead = new TreeLinkNode(0);
TreeLinkNode pre = dummyHead;
while (root != null) {
if (root.left != null) {
pre.next = root.left;
pre = pre.next;
}
if (root.right != null) {
pre.next = root.right;
pre = pre.next;
}
root = root.next;
if (root == null) {
pre = dummyHead;
root = dummyHead.next;
dummyHead.next = null;
}
}
}