Adrita

task 1,2( ds lab 7) 3rd sem

Jul 6th, 2020
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int y;
  4. struct node
  5. {
  6. int data;
  7. struct node* left;
  8. struct node* right;
  9. };
  10. typedef struct node Node;
  11. Node* create_node(int item)
  12. {
  13. Node* new_node=new Node();
  14. if(new_node==NULL)
  15. cout<<"Error"<<endl;
  16. else
  17. {
  18. new_node->data=item;
  19. new_node->left=new_node->right=NULL;
  20. }
  21. return new_node;
  22. }
  23. void inorder(Node* x)
  24. {
  25. if(x!=NULL)
  26. {
  27. inorder(x->left);
  28. cout<<x->data<<" ";
  29. inorder(x->right);
  30. }
  31. }
  32. Node* insert_key(Node* x,int key)
  33. {
  34. Node* new_node=create_node(key);
  35. if(x==NULL)
  36. return new_node;
  37. if(key>x->data+3)
  38. {
  39. x->right=insert_key(x->right,key);
  40. }
  41. else if(key<x->data-3)
  42. {
  43. x->left=insert_key(x->left,key);
  44. }
  45. else
  46. y=0;
  47. return x;
  48. }
  49. void printlevelorder(Node * x)
  50. {
  51. if(x==NULL)
  52. return;
  53. queue<Node*>q;
  54. q.push(x);
  55. while(q.empty()==false)
  56. {
  57. Node* y=q.front();
  58. cout<<y->data<<" ";
  59. q.pop();
  60. if (y->left != NULL)
  61. q.push(y->left);
  62. if (y->right != NULL)
  63. q.push(y->right);
  64. }
  65. }
  66. int main()
  67. {
  68. Node* root=NULL;
  69. while(1)
  70. {
  71. int n;
  72. cin>>n;
  73. y=1;
  74. if(n!=-1)
  75. {
  76. root=insert_key(root,n);
  77. inorder(root);
  78. if(y==0)
  79. cout<<"(Reservation failed)"<<endl;
  80. else
  81. cout<<endl;
  82. }
  83. else
  84. break;
  85. }
  86. cout<<"Level order traversed:"<<endl;
  87. printlevelorder(root);
  88. }
Add Comment
Please, Sign In to add comment