递归
Node* connect(Node* root) {
if(root &&(root->left || root->right))
{
if(root->left && root->right)
{
root->left->next = root->right;
}
Node* pretail = root->right ? root->right : root->left;
Node* node = root->next;
while(node and not(node->left || node->right))
{
node = node->next;
}
if(node)
{
pretail->next = node->left ? node->left : node->right;
}
//先迭代右子树,把next都确定了,否则会导致next没有子树时,找next的next找不到
connect(root->right);
connect(root->left);
}
return root;
}
非递归
1.每一层新建一个空节点head,通过head->next来保存每层的第一个节点。
2.新建一个节点tail,用来遍历每层的节点,通过tail->next链接该层所有节点。
3.当每层节点遍历完,通过cur=head->next移到下一层。
Node* connect(Node* root) {
Node* cur = root;
while(cur)
{
Node* head = new Node(-1);
Node* tail = head;
while(cur)//层遍历
{
if(cur->left)
{
tail->next = cur->left;
tail = tail->next;
}
if(cur->right)
{
tail->next = cur->right;
tail = tail->next;
}
cur = cur->next;
}
cur = head->next;//下一层起始
}
return root;
}