//
// main.cpp
// BFS Binary Tree
//
// Created by Himanshu on 26/08/21.
//
#include <iostream>
#include <queue>
using namespace std;
struct node {
int value = 0;
struct node *left, *right;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->value = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
void BFS (Node *root) {
if (root == NULL) {
return;
}
queue<Node*> qu;
qu.push(root);
int level = 0;
cout<<"Level order traversal:";
while (!qu.empty()) {
int size = (int) qu.size();
cout<<endl<<"Level: "<<level<<endl;
for (int i=0; i<size; i++) {
Node* curr = qu.front();
cout<<(curr->value)<<" ";
qu.pop();
if (curr->left) {
qu.push(curr->left);
}
if (curr->right) {
qu.push(curr->right);
}
}
level++;
}
cout<<endl;
}
int main() {
Node *root = newNode(1);
root->left = newNode(20);
root->right = newNode(21);
root->right->left = newNode(30);
root->right->right = newNode(31);
BFS (root);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBCRlMgQmluYXJ5IFRyZWUKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjYvMDgvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxxdWV1ZT4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnN0cnVjdCBub2RlIHsKICAgIGludCB2YWx1ZSA9IDA7CiAgICBzdHJ1Y3Qgbm9kZSAqbGVmdCwgKnJpZ2h0Owp9Owp0eXBlZGVmIHN0cnVjdCBub2RlIE5vZGU7Cgpub2RlKiBuZXdOb2RlKGludCBkYXRhKQp7CiAgICBub2RlKiBOb2RlID0gbmV3IG5vZGUoKTsKICAgIE5vZGUtPnZhbHVlID0gZGF0YTsKICAgIE5vZGUtPmxlZnQgPSBOVUxMOwogICAgTm9kZS0+cmlnaHQgPSBOVUxMOwogCiAgICByZXR1cm4oTm9kZSk7Cn0KCnZvaWQgQkZTIChOb2RlICpyb290KSB7CiAgICBpZiAocm9vdCA9PSBOVUxMKSB7CiAgICAgICAgcmV0dXJuOwogICAgfQogICAgcXVldWU8Tm9kZSo+IHF1OwogICAgcXUucHVzaChyb290KTsKICAgIGludCBsZXZlbCA9IDA7CiAgICBjb3V0PDwiTGV2ZWwgb3JkZXIgdHJhdmVyc2FsOiI7CiAgICB3aGlsZSAoIXF1LmVtcHR5KCkpIHsKICAgICAgICBpbnQgc2l6ZSA9IChpbnQpIHF1LnNpemUoKTsKICAgICAgICBjb3V0PDxlbmRsPDwiTGV2ZWw6ICI8PGxldmVsPDxlbmRsOwogICAgICAgIGZvciAoaW50IGk9MDsgaTxzaXplOyBpKyspIHsKICAgICAgICAgICAgIE5vZGUqIGN1cnIgPSBxdS5mcm9udCgpOwogICAgICAgICAgICAgY291dDw8KGN1cnItPnZhbHVlKTw8IiAiOwogICAgICAgICAgICAgcXUucG9wKCk7CiAgICAgICAgICAgICBpZiAoY3Vyci0+bGVmdCkgewogICAgICAgICAgICAgICAgIHF1LnB1c2goY3Vyci0+bGVmdCk7CiAgICAgICAgICAgICB9CiAgICAgICAgICAgICBpZiAoY3Vyci0+cmlnaHQpIHsKICAgICAgICAgICAgICAgICBxdS5wdXNoKGN1cnItPnJpZ2h0KTsKICAgICAgICAgICAgIH0KICAgICAgICB9CiAgICAgICAgbGV2ZWwrKzsKICAgIH0KICAgIGNvdXQ8PGVuZGw7Cn0KCmludCBtYWluKCkgewogICAgTm9kZSAqcm9vdCA9IG5ld05vZGUoMSk7CiAgICByb290LT5sZWZ0ID0gbmV3Tm9kZSgyMCk7CiAgICByb290LT5yaWdodCA9IG5ld05vZGUoMjEpOwogICAgcm9vdC0+cmlnaHQtPmxlZnQgPSBuZXdOb2RlKDMwKTsKICAgIHJvb3QtPnJpZ2h0LT5yaWdodCA9IG5ld05vZGUoMzEpOwogICAgQkZTIChyb290KTsKICAgIHJldHVybiAwOwp9Cg==