# Simple 40ms c++ o(n) ,o(1) solution with only one while loop

• Thanks for liji94188 for adding the explanation:

It's a BFS traversal. now pointer is the current level traveler and head is the left most element at next level and the tail is the right most element at next level till now. We move now pointer at current level and populate the the next-link at its children level. (Here the gist is we can move now to its next because this relationship was already populated in the previous round).

``````void connect(TreeLinkNode *root) {

now = root;
while(now)
{
if (now->left)
if (tail) tail = tail->next =now->left;
else head = tail = now->left;
if (now->right)
if (tail) tail = tail->next =now->right;
else head = tail = now->right;
if(!(now = now->next))
{
}
}
}``````

• ``````if(!(now = now->next))
``````

What are you check here?

• I am checking if now->next is empty
And at the same time move now to now->next

It run now=now ->next first and then return now

• This post is deleted!

• where is the explanations then?

• Hi rabeeh, It's a BFS traversal. now pointer is the current level traveler and head is the left most element at next level and the tail is the right most element at next level till now. We move now pointer at current level and populate the the next-link at its children level. (Here the gist is we can move now to its next because this relationship was already populated in the previous round).

• It's a BFS traversal. now pointer is the current level traveler and head is the left most element at next level and the tail is the right most element at next level till now. We move now pointer at current level and populate the the next-link at its children level. (Here the gist is we can move now to its next because this relationship was already populated in the previous round).

• Thanks! That is an excellent job explaining it.

• Hi aileengw, it was me who to say thank you for sharing such cool solution :)

• No problem :)

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