Hi, I am having a problem with my program. It does not insert anything to the tree. Any help are appreciated. Thanks in advance.
driver:
insert function:Code:int main(void) { TreeNode *root; system("clear"); Introduction(); CreateTree(&root); /*endless loop: DoCommand() will call exit() to end the program. */ while(TRUE) DoCommand(GetCommand(), root); return 1; //This statement should never be executed. } void DoCommand(char command, TreeNode *root) { TreeEntry target; // search item int flag; // records EOF condition from scanf FILE *fp; // pointer to file to open char file[MAXCHAR]; // file name to be opened char c; int i; TreeNode *newnode, *targetnode; switch(command) { /* Reading File */ case 'r': printf("\nEnter the filename: "); scanf("%s", file); if((fp = fopen(file,"r")) == NULL) Error("File failed to open.\n"); else { /* Read file */ newnode = (TreeNode*)malloc(sizeof(TreeNode)); while(fscanf(fp, "%s", &newnode->entry.key) != EOF) { if(newnode) { /* Inserting item into tree */ root = InsertTree(root, newnode); printf("newnode = %s\n", newnode); newnode = (TreeNode *)malloc(sizeof(TreeNode)); else printf("memory exhausted.\n"); } } fclose(fp); break; } }
Code:/* InsertTree: insert a new node in the tree. * Pre: The binary search tree to which root points has been created. * The parameter newnode points to a node that has been created and * contains a key in its entry. * Post: The node newnode has been inserted into the tree in such a * way that the properties of a binary search tree are preserved. */ TreeNode *InsertTree(TreeNode *root, TreeNode *newnode) { if(!root) { root = newnode; root->left = root->right = NULL; } else if (LT(newnode->entry.key, root->entry.key)) root->left = InsertTree(root->left, newnode); else root->right = InsertTree(root->right, newnode); return root; }