Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 25 additions & 15 deletions Trees/Leetcode-116. Populating Next Right Pointers in Each Node.cpp
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
class Solution {
public:

Node* connect(Node* root) {
if(root==NULL)
return NULL;

if(root->left){
root->left->next=root->right;

if(root->next){
root->right->next=root->next->left;
}

connect(root->left);
connect(root->right);
if (!root) return NULL;

Node* leftmost = root; // Start at the root level

while (leftmost) {
Node* dummy = new Node(0); // Dummy node for next level
Node* temp = dummy; // Pointer to build next level links

Node* curr = leftmost;
while (curr) {
if (curr->left) {
temp->next = curr->left;
temp = temp->next;
}
if (curr->right) {
temp->next = curr->right;
temp = temp->next;
}
curr = curr->next; // Move to next node in current level
}

leftmost = dummy->next; // Move to next level
delete dummy; // Free dummy node
}

return root;

}
};
};