fork download
  1. // title:Level Order Traversal
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. struct BSTNode{
  7. int val;
  8. BSTNode *left, *right;
  9. BSTNode(int val){
  10. this->val = val;
  11. this->left = this->right = NULL;
  12. }
  13. };
  14. struct BSTNode * insert(struct BSTNode * root,int n)
  15. {
  16. if(root==NULL)
  17. return new BSTNode(n);
  18. else if(n<root->val)
  19. root->left=insert(root->left,n);
  20. else if(root->val<n)
  21. root->right=insert(root->right,n);
  22. return root;
  23. }
  24. void level(struct BSTNode *root)
  25. {
  26.  
  27. if(root!=NULL)
  28. {
  29. queue<BSTNode*>q;
  30. q.push(root);
  31. while(q.size()!=0)
  32. {
  33. int l=q.size();
  34. // cout<<"1";
  35. for(int i=0;i<l;i++)
  36. {
  37. // cout<<"aqghsz";
  38. BSTNode *x=q.front();
  39. q.pop();
  40. cout<<x->val<<" ";
  41. if(x->left)
  42. q.push(x->left);
  43. if(x->right)
  44. q.push(x->right);
  45. }
  46. cout<<"\n";
  47. }
  48. }
  49. }
  50. int main()
  51. {
  52. int tq;
  53. cin>>tq;
  54. while(tq--)
  55. {
  56. int n;
  57. cin>>n;
  58. struct BSTNode *root=NULL;
  59. for(int i=0;i<n;i++)
  60. {
  61. int x;
  62. cin>>x;
  63. root=insert(root,x);
  64. }
  65.  
  66. level(root);
  67. cout<<"\n";
  68. }
  69. }
Success #stdin #stdout 0.01s 5520KB
stdin
4
5
1 2 3 4 5 
5
3 2 4 1 5 
7
4 5 15 0 1 7 17
3
3 4 1
stdout
1 
2 
3 
4 
5 

3 
2 4 
1 5 

4 
0 5 
1 15 
7 17 

3 
1 4