1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <stdio.h> #include <stdlib.h> #include <string.h>
typedef struct TreeNode { char *s; struct TreeNode *Left; struct TreeNode *Right; } BinTree;
BinTree* TreeInsert(char *s, BinTree *T) { if (T == NULL) { T = (BinTree*)malloc(sizeof(BinTree)); if (T == NULL) { printf("Memory allocation failed\n"); exit(EXIT_FAILURE); } T->s = strdup(s); T->Left = T->Right = NULL; } else if (strcmp(s, T->s) < 0) { T->Left = TreeInsert(s, T->Left); } else if (strcmp(s, T->s) > 0) { T->Right = TreeInsert(s, T->Right); } return T; }
void InOrderTraversal(BinTree *T) { if (T != NULL) { InOrderTraversal(T->Left); printf("%s\n", T->s); InOrderTraversal(T->Right); } }
void FreeTree(BinTree *T) { if (T != NULL) { FreeTree(T->Left); FreeTree(T->Right); free(T->s); free(T); } }
int main() { char* months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; BinTree *T = NULL; for (int i = 0; i < 12; i++) { T = TreeInsert(months[i], T); } printf("Inorder traversal of BST:\n"); InOrderTraversal(T); FreeTree(T); return 0; }
|