fork download
  1. //
  2. // main.cpp
  3. // BFS Binary Tree
  4. //
  5. // Created by Himanshu on 26/08/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <queue>
  10. using namespace std;
  11.  
  12. struct node {
  13. int value = 0;
  14. struct node *left, *right;
  15. };
  16. typedef struct node Node;
  17.  
  18. node* newNode(int data)
  19. {
  20. node* Node = new node();
  21. Node->value = data;
  22. Node->left = NULL;
  23. Node->right = NULL;
  24.  
  25. return(Node);
  26. }
  27.  
  28. void BFS (Node *root) {
  29. if (root == NULL) {
  30. return;
  31. }
  32. queue<Node*> qu;
  33. qu.push(root);
  34. int level = 0;
  35. cout<<"Level order traversal:";
  36. while (!qu.empty()) {
  37. int size = (int) qu.size();
  38. cout<<endl<<"Level: "<<level<<endl;
  39. for (int i=0; i<size; i++) {
  40. Node* curr = qu.front();
  41. cout<<(curr->value)<<" ";
  42. qu.pop();
  43. if (curr->left) {
  44. qu.push(curr->left);
  45. }
  46. if (curr->right) {
  47. qu.push(curr->right);
  48. }
  49. }
  50. level++;
  51. }
  52. cout<<endl;
  53. }
  54.  
  55. int main() {
  56. Node *root = newNode(1);
  57. root->left = newNode(20);
  58. root->right = newNode(21);
  59. root->right->left = newNode(30);
  60. root->right->right = newNode(31);
  61. BFS (root);
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 5552KB
stdin
Standard input is empty
stdout
Level order traversal:
Level: 0
1 
Level: 1
20 21 
Level: 2
30 31