# 24ms Easy Iterative and Recursive C++ Solutions

• The idea is similar to a level-order traversal and remember to take full advantages of the prefect binary tree assumption in the problem statement.

The code (iterative solution) is as follows.

class Solution {
public:
while (pre) {
cur = pre;
while (cur && cur -> left) {
cur -> left -> next = cur -> right;
if (cur -> next)
cur -> right -> next = cur -> next -> left;
cur = cur -> next;
}
pre = pre -> left;
}
}
};

This problem can also be solved recursively.

class Solution {
public:
if (!root) return;
if (root -> left) {
root -> left -> next = root -> right;
if (root -> next)
root -> right -> next = root -> next -> left;
}
connect(root -> left);
connect(root -> right);
}
};

• Recursive solution does not use constant space, so only iterative solution should be used

• Hi, hpplayer. Yeah, you're right. That's just for the completeness of solution sharing :-)

• straightforward but O(N) space

class Solution {
public:
if(!root) return;
out.push(root);

while(!outqueue.empty())
{
outqueue.pop();
if(!outqueue.empty()) tem->next = outqueue.front();
if(tem->left) inqueue.push(tem->left);
if(tem->right) inqueue.push(tem->right);
if(outqueue.empty())
{