fork download
  1. #include<iostream>
  2. #include<stdlib.h>
  3. #include<queue>
  4. using namespace std;
  5.  
  6. class node
  7. {
  8. public:
  9.  
  10. node *left, *right;
  11. int data;
  12.  
  13. };
  14.  
  15. class Breadthfs
  16. {
  17.  
  18. public:
  19.  
  20. node *insert(node *, int);
  21. void bfs(node *);
  22.  
  23. };
  24.  
  25. node *insert(node *root, int data)
  26. // inserts a node in tree
  27. {
  28.  
  29. if(!root)
  30. {
  31.  
  32. root=new node;
  33. root->left=NULL;
  34. root->right=NULL;
  35. root->data=data;
  36. return root;
  37. }
  38.  
  39. queue<node *> q;
  40. q.push(root);
  41.  
  42. while(!q.empty())
  43. {
  44.  
  45. node *temp=q.front();
  46. q.pop();
  47.  
  48. if(temp->left==NULL)
  49. {
  50.  
  51. temp->left=new node;
  52. temp->left->left=NULL;
  53. temp->left->right=NULL;
  54. temp->left->data=data;
  55. return root;
  56. }
  57. else
  58. {
  59.  
  60. q.push(temp->left);
  61.  
  62. }
  63.  
  64. if(temp->right==NULL)
  65. {
  66.  
  67. temp->right=new node;
  68. temp->right->left=NULL;
  69. temp->right->right=NULL;
  70. temp->right->data=data;
  71. return root;
  72. }
  73. else
  74. {
  75.  
  76. q.push(temp->right);
  77.  
  78. }
  79.  
  80. }
  81.  
  82. }
  83.  
  84. void bfs(node *head)
  85. {
  86.  
  87. queue<node*> q;
  88. q.push(head);
  89.  
  90. int qSize;
  91.  
  92. while (!q.empty())
  93. {
  94. qSize = q.size();
  95. #pragma omp parallel for
  96. //creates parallel threads
  97. for (int i = 0; i < qSize; i++)
  98. {
  99. node* currNode;
  100. #pragma omp critical
  101. {
  102. currNode = q.front();
  103. q.pop();
  104. cout<<"\t"<<currNode->data;
  105.  
  106. }// prints parent node
  107. #pragma omp critical
  108. {
  109. if(currNode->left)// push parent's left node in queue
  110. q.push(currNode->left);
  111. if(currNode->right)
  112. q.push(currNode->right);
  113. }// push parent's right node in queue
  114.  
  115. }
  116. }
  117.  
  118. }
  119.  
  120. int main(){
  121.  
  122. node *root=NULL;
  123. int data;
  124. char ans;
  125.  
  126. do
  127. {
  128. cout<<"\n enter data=>";
  129. cin>>data;
  130.  
  131. root=insert(root,data);
  132.  
  133. cout<<"do you want insert one more node?";
  134. cin>>ans;
  135.  
  136. }while(ans=='y'||ans=='Y');
  137.  
  138. bfs(root);
  139.  
  140. return 0;
  141. }
  142.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
 enter data=>do you want insert one more node?	32764