fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Node {
  5. int data;
  6. struct Node* left;
  7. struct Node* right;
  8. };
  9.  
  10. struct Node* createNode(int data) {
  11. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
  12. newNode->data = data;
  13. newNode->left = NULL;
  14. newNode->right = NULL;
  15. return newNode;
  16. }
  17.  
  18. struct Node* insert(struct Node* root, int data) {
  19. if (root == NULL) {
  20. return createNode(data);
  21. } else {
  22. if (data <= root->data) {
  23. root->left = insert(root->left, data);
  24. } else {
  25. root->right = insert(root->right, data);
  26. }
  27. return root;
  28. }
  29. }
  30.  
  31. void preorder(struct Node* root) {
  32. if (root != NULL) {
  33. printf("%d ", root->data);
  34. preorder(root->left);
  35. preorder(root->right);
  36. }
  37. }
  38.  
  39. void inorder(struct Node* root) {
  40. if (root != NULL) {
  41. inorder(root->left);
  42. printf("%d ", root->data);
  43. inorder(root->right);
  44. }
  45. }
  46.  
  47. void postorder(struct Node* root) {
  48. if (root != NULL) {
  49. postorder(root->left);
  50. postorder(root->right);
  51. printf("%d ", root->data);
  52. }
  53. }
  54.  
  55. int main() {
  56. struct Node* root = NULL;
  57. char choice;
  58. int data;
  59.  
  60. do {
  61. printf("Enter data for node: ");
  62. scanf("%d", &data);
  63. root = insert(root, data);
  64.  
  65. printf("Do you want to enter more nodes? (Y/N): ");
  66. scanf(" %c", &choice);
  67. } while (choice == 'Y' || choice == 'y');
  68.  
  69. printf("\nEnter traversal choice (P for preorder, I for inorder, O for postorder): ");
  70. scanf(" %c", &choice);
  71.  
  72. switch(choice) {
  73. case 'P':
  74. case 'p':
  75. printf("Preorder traversal: ");
  76. preorder(root);
  77. break;
  78. case 'I':
  79. case 'i':
  80. printf("Inorder traversal: ");
  81. inorder(root);
  82. break;
  83. case 'O':
  84. case 'o':
  85. printf("Postorder traversal: ");
  86. postorder(root);
  87. break;
  88. default:
  89. printf("Invalid choice!");
  90. }
  91.  
  92. return 0;
  93. }
  94.  
  95.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Enter data for node: Do you want to enter more nodes? (Y/N): 
Enter traversal choice (P for preorder, I for inorder, O for postorder): Invalid choice!