My recursive solution

• ``````void connect(TreeLinkNode *root) {
if( root == NULL || root->left == NULL && root->right == NULL )        //{} \ {0}
{
return;
}

p = root->left;
q = root->right;
p->next = q;
while( p->right != NULL )
{
p = p->right;
q = q->left;
p->next = q;
}

connect( root->left );
connect( root->right );
}``````

• not clear about your recursive code, could you explain how do you divide the original problem into 2 sub problem?

• This post is deleted!

• Sorry I can not drow a tree here, it's a little difficult to show you. I write my method in my blog. Hope it can help you.

• The code looks okay. However, it uses extra current stack memory. You may want to go on to consider a pure iterative solution which uses constant memory.

• I know you meaning, your recursive seems elegant, but it is only suitable for perfect BT, what if not, it may be incorrect....

• If the input tree is just a single node then its next has to be set as NULL.
But in your code, it doesn't happen as the first return statement will be executed.
However your code was accepted, when I submitted.
Please correct me if I am wrong.

• Yes, you can set the root->next to NULL if there is just a single node. I think my code was accept because all the next of the nodes are NULL as default. So you didn't have to reset it to NULL.

• Ohh yes. I forget the initial status of next ptr. Thanks for the reply @jwang8

• This post is deleted!

• Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the FAQ for more info. Take a look at good sharing example

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.