Binary tree implementation in C question as found in K&R -
so i've been reading through k&r c book , have question.. in 6th chapter on structs on page 140-141, there code looks (i took out of more irrelevant parts)
/* program loops through tree looking word if finds word itll incremenet count 1 if doesnt itll add new node */ 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) /* getword grabs 1 word @ time file of words */ if(isalpha(word[0])) /* isalpha checks see if valid word */ root = addnode(root, word); treeprint(root); /* prints tree */ return 0; } struct node *addnode(struct node *p, char *w) { int cond; if(p == null) { p = malloc(sizeof(struct node)); /* allocates memory new 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 confusion in main() function @ root = addnode(root, word)
if addnode returns pointer newly added node (or node word @ if int tree), wouldn't "lose" data above tree? shouldn't root stay root of tree?
thanks!
root staying root of tree. root passed first parameter of addnode malloc if null, i.e. when root passed first time. in later calls won't change root, modify count, left or right. note in recursive addnode calls p not passed, rather it's left or right child passed. try go through tree paper , pencil/pen , realize how nodes getting added.
Comments
Post a Comment