Advertisement
Guest User

Untitled

a guest
May 30th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node
  4. { int value;
  5. struct node* left;
  6. struct node* right;};
  7. void search(struct node* r,int number);
  8. struct node* root;
  9. struct node* insert(struct node* r, int data);
  10. void inOrder(struct node* r);
  11. void preOrder(struct node* r);
  12. void postOrder(struct node* r);
  13. int main()
  14. { root = NULL;
  15. int n, v,i,c,e,ele;
  16. c=1;
  17. while(c!=4)
  18. {
  19. printf("Enter your choice :\n1.Insert\n2.Search\n3.Recursive Traversal\n4.Exit\n");
  20. scanf("%d",&c);
  21. if(c==1)
  22. {
  23. printf("Enter the element to insert : ");
  24. scanf("%d",&ele);
  25. root=insert(root,ele);
  26. }
  27. else if(c==2)
  28. {
  29. printf("\nEnter the element to search : ");
  30. scanf("%d",&ele);
  31. search(root,ele);
  32. }
  33. else if(c==3)
  34. {
  35. printf("Enter your choice :\n1.Preorder\n2.Postorder\n3.Inorder\n");
  36. scanf("%d",&n);
  37. if(n==1)
  38. {
  39. printf("Preorder Traversal: ");
  40. preOrder(root);
  41. }
  42. else if(n==2)
  43. {
  44. printf("Postorder Traversal: ");
  45. postOrder(root);
  46. printf("\n");
  47.  
  48. }
  49. else
  50. {
  51. printf("Inorder Traversal: ");
  52. inOrder(root);
  53. printf("\n");
  54. }
  55. }
  56. return 0;
  57. }
  58.  
  59. struct node* insert(struct node* r, int data)
  60. {
  61. if(r==NULL)
  62. {
  63. r = (struct node*) malloc(sizeof(struct node));
  64. r->value = data;
  65. r->left = NULL;
  66. r->right = NULL;
  67. }
  68. else if(data < r->value){
  69. r->left = insert(r->left, data);
  70. }
  71. else {
  72. r->right = insert(r->right, data);
  73. }
  74. return r;
  75.  
  76. }
  77.  
  78. void inOrder(struct node* r)
  79. {
  80. if(r!=NULL){
  81. inOrder(r->left);
  82. printf("%d ", r->value);
  83. inOrder(r->right);
  84. }
  85. }
  86.  
  87. void preOrder(struct node* r)
  88. {
  89. if(r!=NULL){
  90. printf("%d ", r->value);
  91. preOrder(r->left);
  92. preOrder(r->right);
  93. }
  94. }
  95.  
  96. void postOrder(struct node* r)
  97. {
  98. if(r!=NULL){
  99. postOrder(r->left);
  100. postOrder(r->right);
  101. printf("%d ", r->value);
  102.  
  103. }
  104. }
  105. void search(struct node* root,int number)
  106. {
  107. if(root==NULL){
  108. printf("The tree is empty\n");
  109. }
  110. else if(root->value==number){
  111. printf("The data is found\n");
  112. }
  113. else if(number<=root->value){
  114. return search(root->left,number);
  115. }
  116. else{
  117. return search(root->right,number);
  118. }
  119.  
  120.  
  121. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement