可以用队列层序遍历,但空间复杂度是O(N)
class Solution {
public:
void connect(TreeLinkNode *root)
{
if(root==NULL)
return;
queue<TreeLinkNode *>q;
q.push(root);
q.push(NULL);
while(!q.empty())
{
TreeLinkNode *temp=q.front();
q.pop();
if(temp)
{
temp->next=q.front();
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
else
{
if(q.empty())
return;
q.push(NULL);
}
}
}
};
第二种方式:深度优先遍历,但不同于116题的完美二叉树,这题要先把右子树递归,再递归左子树
class Solution
{
public:
void connect(TreeLinkNode *root)
{
if(root==NULL)
return;
TreeLinkNode *curnext=root->next;
TreeLinkNode *p=NULL;
while(curnext)
{
if(curnext->left)
{
p=curnext->left;
break;
}
if(curnext->right)
{
p=curnext->right;
break;
}
curnext=curnext->next;
}
if(root->right)
root->right->next=p;
if(root->left)
{
if(root->right)
root->left->next=root->right;
else
root->left->next=p;
}
connect(root->right);
connect(root->left);
}
};