So, I read the K & RC book and ask a question .. in the 6th chapter on structures on pages 140-141, there is a code that looks like this (I took out some of the more non-local parts)
struct node { char *word; int count; struct node *left; struct node *right; } main() { struct node *root; char word[1000]; root = NULL; while(getword(word, MAXWORD) != EOF) if(isalpha(word[0])) root = addNode(root, word); treeprint(root); return 0; } struct node *addNode(struct node *p, char *w) { int cond; if(p == NULL) { p = malloc(sizeof(struct node)); p -> word = strdup(w); p -> count = 1; p -> left = p -> right = NULL; } else if ((cond = strcmp(w, p -> word)) == 0) p -> count++; else if(cond < 0) p -> left = addNode(p -> left, w); else p -> right = addNode(p -> right, w); return p; }
And my confusion in the main () function in the root = addNode (root, word)
If addNode returns a pointer to a newly added node (or to a node if it already has an int he tree), has this not "lost" all the data above the tree? Shouldn't the root remain the root of the tree?
Thanks!
source share