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
思路:
两种方案:1 通过队列的方式;2 利用中间变量
1 通过队列的方式
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode *> q;
q.push(root);
TreeLinkNode *last = root;
while (q.size()){
TreeLinkNode* curr = q.front();
q.pop();
if (curr->left) q.push(curr->left);
if (curr->right) q.push(curr->right);
if (last == curr){
if (q.size()) last = q.back();
}
else{
curr->next = q.front();
}
}
}
2 利用中间变量
void connect2(TreeLinkNode *root){
if (!root) return;
while (root){
TreeLinkNode *next = NULL;
TreeLinkNode *pre = NULL;
next = root;
while (next){
if (next->left) { next = next->left; break; }
if (next->right){ next = next->right; break; }
next = next->next;
}
while (root){
if (root->left){
if (pre) pre->next = root->left;
pre = root->left;
}
if (root->right){
if (pre) pre->next = root->right;
pre = root->right;
}
root = root->next;
}
root = next;
}
}