Populating Next Right Pointers in Each Node II
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. Recursive approach is fine, implicit stack space does not count as extra space for this problem. 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
Solution: Recursive
We find the next node first If right child is not null, we set right child's next pointer. If left child is not null, we set left child's next pointer.
void connect(TreeLinkNode *root) {
if (!root) return;
TreeLinkNode *node = root->next;
while (node) {
if (node->left) {
node = node->left;
break;
}
if (node->right) {
node = node->right;
break;
}
node = node->next;
}
if (root->right) root->right->next = node;
if (root->left) root->left->next = root->right ? root->right : node;
connect(root->right);
connect(root->left);
}
Solution: Iterative
We can use level order traversal to update each node.
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> q;
q.push(root);
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len; ++i) {
TreeLinkNode *t = q.front(); q.pop();
if (i < len - 1) t->next = q.front();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
}