求C语言版数据结构二叉树的先序遍历递归算法,不要伪码,要求能实现能运行的。谢过各位大佬了!
1个回答
2017-05-01
展开全部
K&R中的一个实现,可以读取数字,插入二叉树,并且统计出现次数。最后输出,这里假设只读取正数,自己可以改getword函数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAXLINE 100
struct num {
int number;
int count;
struct num *left;
struct num *right;
} ;
struct num *addtree(struct num *, char w[]);
void treeprint(struct num *);
int getword(char w[], int lim);
int main(void)
{
struct num *root;
char word[MAXLINE];
root = NULL;
while (getword(word, MAXLINE) != EOF)
if (isdigit(word[0]))
root = addtree(root, word);
treeprint(root);
return 0;
}
int getword(char *word, int lim)
{
int c;
int getch();
void ungetch();
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (!isdigit(c)) {
*w = '\0';
return c;
}
for (; --lim > 0; w++) {
if (!isdigit(c = *w = getch())) {
ungetch(c);
break;
}
}
*w = '\0';
return word[0];
}
struct num *talloc(void);
struct num *addtree(struct num *p, char *w)
{
int cond;
cond = atoi(w);
// printf("---%d---\n", cond);
if (p == NULL) {
p = talloc();
p->number = cond;
p->count = 1;
p->left = p->right = NULL;
} else if (cond == p->number)
p->count++;
else if (cond < p->number)
p->left = addtree(p->left, w);
else
p->right = addtree(p->right, w);
return p;
}
void treeprint(struct num *p)
{
if (p != NULL) {
treeprint(p->left);
printf("%d\thas:%d\n", p->number, p->count);
treeprint(p->right);
}
}
struct num *talloc(void)
{
return (struct num *) malloc(sizeof(struct num));
}
#define BUFSIZE 100
int bufp = 0;
char bufline[BUFSIZE];
int getch(void)
{
return (bufp > 0) ? bufline[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp < BUFSIZE)
bufline[bufp++] = c;
else
printf("error : full\n");
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询