What are Level Order Siblings?
Before we dive into the ways of connecting level order siblings, let's understand what level order siblings actually are. In a binary tree, level order siblings are the nodes that are present at the same level and have the same parent. For example, consider the binary tree below:
Connecting Level Order Siblings using Pointers
One of the ways to connect level order siblings is by using pointers. We can maintain a pointer to the previous node at the same level while traversing the tree in a level order manner. Let's see how we can implement this: void connect(Node* root) {
if(!root) return;
queue
q.push(root);
while(!q.empty()){
int n = q.size();
Node* prev = NULL;
for(int i=0;i
q.pop();
if(prev) prev->nextRight = curr;
prev = curr;
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
}
prev->nextRight = NULL;
}
}
Connecting Level Order Siblings using Recursion
Another way to connect level order siblings is by using recursion. We can pass the pointer to the next node at the same level while traversing the tree in a level order manner. Let's see how we can implement this: void connect(Node* root) {
if(!root) return;
if(root->left) root->left->nextRight = root->right;
if(root->right) root->right->nextRight = root->nextRight ? root->nextRight->left : NULL;
connect(root->left);
connect(root->right);
}
Komentar
Posting Komentar