class Solution {
public:
void connect(TreeLinkNode *root) {
if(!root)return ;
if(root->left)
root->left->next=root->right;
if(root->right)
root->right->next=(root->next)?root->next->left:NULL;
connect(root->left);
connect(root->right);
}
};
做2的时候想仿照1时候的做法,但是因为需要把上一层连接完后,才能连接下一层,所以写了几十行废话。参照了这个:
http://www.cnblogs.com/remlostime/archive/2012/11/25/2787857.html
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==NULL)
return ;
TreeLinkNode *p,*q,*nextnode;
p=root;
q=nextnode=NULL;
while(p)
{
if(p->left)
{
if(q)
q->next=p->left;
if(nextnode==NULL)
nextnode=p->left;
q=p->left;
}
if(p->right)
{
if(q)
q->next=p->right;
if(nextnode==NULL)
nextnode=p->right;
q=p->right;
}
p=p->next;
}
connect(nextnode);
}
};