Advertisement
Guest User

Untitled

a guest
Feb 14th, 2015
279
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define MAXLEN 15
  5.  
  6. typedef struct treeNode{
  7. char string[MAXLEN+1];
  8. struct treeNode *left;
  9. struct treeNode *right;
  10. }treeNode;
  11.  
  12. treeNode * insert(treeNode *node, char s[MAXLEN]){
  13. puts("running insert");
  14. if(node == NULL){
  15. node = (treeNode *)malloc(sizeof(treeNode));
  16. strncpy(node -> string, s, MAXLEN);
  17. node -> left = NULL;
  18. node -> right = NULL;
  19. }
  20.  
  21. else if(strcmp(node->string, s)>0){
  22. node -> right = insert(node->right, s);
  23. }
  24. else if(strcmp(node->string, s)<0){
  25. node -> left = insert(node->left, s);
  26. }
  27. else if(strcmp(node->string, s) == 0){
  28. node -> left = insert(node->left, s);
  29. }
  30.  
  31. return node;
  32.  
  33. }
  34. void treeprint( treeNode *node , FILE *OUTPUT_FILE)
  35. {
  36. if ( node != NULL)
  37. {
  38. treeprint(node->left, OUTPUT_FILE);
  39. fprintf(OUTPUT_FILE , "%s\n" , node->string);
  40. treeprint(node->right , OUTPUT_FILE);
  41. }
  42. }
  43.  
  44. int main(int argc, char *argv[]){
  45.  
  46. treeNode *root = NULL;
  47.  
  48. FILE *ifp;
  49. FILE *ofp;
  50. char s[MAXLEN+1];
  51.  
  52. if(argc != 2){
  53. fprintf(stderr, "Usage: %s file\n", argv[0]); exit(1);
  54. }
  55.  
  56. if((ifp = fopen(argv[1], "r")) == NULL){
  57. fprintf(stderr, "Could not open file: %s\n", argv[1]); exit(1);
  58. }
  59.  
  60. ofp = fopen("output.txt", "w+");
  61.  
  62. while(fscanf(ifp, "%s", &s) != EOF){
  63. root = insert(root, s);
  64. }
  65. treeprint(root, ofp);
  66.  
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement