Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. typedef struct BSTNode{
  6. int value;
  7. struct BSTNode *left;
  8. struct BSTNode *right;
  9. }BSTNode;
  10.  
  11. BSTNode* InsertNode(BSTNode **root, int x){
  12. if (!*root){
  13. *root=malloc(sizeof(BSTNode));
  14. (*root)->value=x;
  15. (*root)->left=NULL;
  16. (*root)->right=NULL;
  17. return (*root);
  18. }
  19. if (x<=(*root)->value)
  20. (*root)->left= InsertNode(&((*root)->left), x);
  21. else
  22. (*root)->right= InsertNode(&((*root)->right),x);
  23. return (*root);
  24. }
  25.  
  26. void Search(BSTNode** root, int x){
  27. if ((*root)==NULL){
  28. printf("NO!\n");
  29. return;
  30. }
  31. if ((*root)->value==x)
  32. printf("YES!\n");
  33. else if ((*root)->value>x)
  34. Search(&((*root)->left), x);
  35. else
  36. Search(&((*root)->right), x);
  37. return;
  38. }
  39.  
  40. void BSTDestroy(BSTNode** root)
  41. {
  42. if(!*root)
  43. return;
  44.  
  45. BSTDestroy(&((*root)->left));
  46. BSTDestroy(&((*root)->right));
  47. free(*root);
  48. *root = NULL;
  49. }
  50.  
  51. void BSTPreOrderPrint(BSTNode** root)
  52. {
  53. if(!*root)
  54. return;
  55.  
  56. printf("%s\n", (*root)->value);
  57. BSTPreOrderPrint(&((*root)->left));
  58. BSTPreOrderPrint(&((*root)->right));
  59. }
  60.  
  61. void BSTInOrderPrint(BSTNode** root)
  62. {
  63. if(!*root)
  64. return;
  65.  
  66. BSTInOrderPrint(&((*root)->left));
  67. printf("%s\n", (*root)->value);
  68. BSTInOrderPrint(&((*root)->right));
  69. }
  70.  
  71. void BSTPostOrderPrint(BSTNode** root)
  72. {
  73. if(!*root)
  74. return;
  75.  
  76. BSTPostOrderPrint(&((*root)->left));
  77. BSTPostOrderPrint(&((*root)->right));
  78. printf("%s\n", (*root)->value);
  79. }
  80.  
  81.  
  82. int main(void){
  83. BSTNode *root=NULL;
  84. int i,x;
  85. for(i = 0; i < 8; i++)
  86. {
  87. scanf("%d", &x);
  88. InsertNode(&root,x);
  89. }
  90.  
  91. BSTPreOrderPrint(&root);
  92. BSTDestroy(&root);
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement