Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
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
题意:把每一层节点链接起来
思路:层次遍历的思想,将一层的元素全部入队,然后将本层每个节点的子节点一次全部入队
class Solution
{
public:
void connect(TreeLinkNode* root)
{
if (root==NULL)
{
return;
}
TreeLinkNode* tail = root;
TreeLinkNode* tmp;
queue<TreeLinkNode*> q;
q.push(root);
while (q.size())
{
tmp = q.front();
q.pop();
if (tmp->left!=NULL)
{
q.push(tmp->left);
}
if (tmp->right!=NULL)
{
q.push(tmp->right);
}
if(tmp==tail)
{
tmp->next = NULL;
tail = q.back();
}
else
{
tmp->next = q.front();
}
}
}
};