so i am new to this programming and i had a doubt on this part of learning it , for two variation problems nearly the code is similar with a little bit of change but i dont understand it clearly.
The Node class type is a standard Tree based structure along with a next self-referential
Connect level order siblings:
class Solution {
public:
Node* connect(Node* root) {
return helper(root);
}
Node* helper(Node* root)
{
if(root==NULL)
return root;
queue<Node*>queue;
queue.push(root);
while(!(queue.empty()))
{
int levelsize=queue.size();
Node* prev=NULL;
for(int i = 0 ; i < levelsize ; i++)
{
Node* current=queue.front();
queue.pop();
if(prev!=NULL)
prev->next=current;
prev=current;
if(current->left!=NULL)
queue.push(current->left);
if(current->right!=NULL)
queue.push(current->right);
}
}
return root;
}
};
Connect all level order siblings:
class Solution {
public:
Node* connect(Node* root)
{
return helper(root);
}
Node* helper(Node* root)
{
if(root==NULL)
return root;
queue<Node*>queue;
queue.push(root);
while(!(queue.empty()))
{
int levelsize=queue.size();
Node* prev=NULL;
Node* current=queue.front();
queue.pop();
if(prev!=NULL)
prev->next=current;
prev=current;
if(current->left!=NULL)
queue.push(current->left);
if(current->right!=NULL)
queue.push(current->right);
}
return root;
}
};