/* File: main8e.c * * Demonstrate binary search tree * This version reads data from a file * and exercises some more functions. * */ #include #include #include "bst2.h" void print_rank(tnode *tree, int r) { tnode *ptr ; ptr = bst_find_by_rank(tree, r) ; if (ptr == NULL) { printf("No such rank: %d\n", r) ; } else { printf("%s (%d)\n", ptr->name, ptr->frequency) ; } } int main() { tnode *tree = NULL ; char filename[256], nom[256] ; FILE *ifile ; int r, freq ; printf("\n\n### Testing bst_insert() ###\n") ; printf("Filename (max 255 char): ") ; scanf("%256s", filename) ; ifile = fopen(filename, "r") ; if (ifile ==NULL) { fprintf(stderr, "Could not open file for reading: %s\n", filename) ; exit(1) ; } while(1) { r = fscanf(ifile, "%256s %d", nom, &freq) ; if (r < 2) break ; // printf("Adding %s, %d\n", nom, freq) ; tree = bst_insert(tree, nom, freq) ; } fclose(ifile) ; printf("-------------------------------------------------------------------\n") ; bst_walk(tree) ; printf("-------------------------------------------------------------------\n") ; // Test rank functions printf("Most popular name: ") ; print_rank(tree, 1) ; printf("Not so popular name (rank=200): ") ; print_rank(tree, 200) ; printf("Rank 100 name: ") ; print_rank(tree, 100) ; printf("Rank 37 name: ") ; print_rank(tree, 37) ; printf("Rank 500 name: ") ; print_rank(tree, 500) ; printf("-------------------------------------------------------------------\n") ; printf("Top 20 names:\n") ; int i ; for(i=1 ;i <= 20 ; i++) { print_rank(tree, i) ; } printf("-------------------------------------------------------------------\n") ; printf("Top 25-30 names:\n") ; for(i=25 ;i <= 30 ; i++) { print_rank(tree, i) ; } printf("-------------------------------------------------------------------\n") ; // Testing find by name and remove tnode *ptr ; int found ; ptr = bst_find_by_name(tree, "Stephanie") ; if (ptr != NULL) { printf("Found %s, deleting ...\n", ptr->name) ; tree = bst_remove(tree, ptr->frequency, &found) ; // hope there are no ties in frequency } ptr = bst_find_by_name(tree, "Brittany") ; if (ptr != NULL) { printf("Found %s, deleting ...\n", ptr->name) ; tree = bst_remove(tree, ptr->frequency, &found) ; // hope there are no ties in frequency } printf("Top 20 names (without Stephanie and Brittany):\n") ; for(i=1 ;i <= 20 ; i++) { print_rank(tree, i) ; } printf("-------------------------------------------------------------------\n") ; bst_destroy(tree) ; return 0 ; }