c语言程序设计中二叉树例子的疑惑<已解决>
程序代码:
#include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #define MAXWORD 100 struct tnode { /* the tree node: */ char *word; /* points to the text */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */ }; struct tnode *addtree(struct tnode *, char *); void treeprint(struct tnode *); int getword(char *, int); /* word frequency count */ main() { char c; struct tnode *root; char word[MAXWORD]; root = NULL; while (scanf("%s",word)!=EOF) root = addtree(root, word);//这里不太理解,root作为根节点要是被更改了,下次操作时又怎么找到根节点呢? treeprint(root); return 0; } struct tnode *talloc(void); char *strdup(char *); /* addtree: add a node with w, at or below p */ struct tnode *addtree(struct tnode *p, char *w) { int cond; if (p == NULL) { /* a new word has arrived */ p = talloc(); /* make a new node */ p->word = strdup(w); p->count = 1; p->left = p->right = NULL; } else if ((cond = strcmp(w, p->word)) == 0) p->count++; /* repeated word */ else if (cond < 0) /* less than into left subtree */ p->left = addtree(p->left, w); else /* greater than into right subtree */ p->right = addtree(p->right, w); return p; } /* treeprint: inorder print of tree p */ void treeprint(struct tnode *p) { if (p != NULL) { treeprint(p->left); printf("%d %s\n", p->count, p->word); treeprint(p->right); } } /* talloc: make a tnode */ struct tnode *talloc(void) { return (struct tnode *) malloc(sizeof(struct tnode)); } char *strdup(char *s) /* make a duplicate of s */ { char *p; p = (char *) malloc(strlen(s)+1); /* +1 for '\0' */ if (p != NULL) strcpy(p, s); return p; }
问题:
main函数里面
root = addtree(root, word)
roo作为根节点每次都被赋了新值,下次又是如何找到根节点的呢
实际运行没有错误
请各位高手指点一下
[ 本帖最后由 阿的个发 于 2012-5-12 20:43 编辑 ]