初心者です。
タイトル通り、再帰呼び出しの2分探索木を作ってまして、以下のようなところまで作ったのですが、「12 15 18 28 31」と入力しても実行結果が1つしか出ません。
おそらくaddtreeの戻り値がおかしいのかと思われますが、他にも違うところがあると思います。
なにをどのようにすればよいでしょうか。
教えてください。
#include<stdio.h>
#include<stdlib.h>
struct tnode{
int value;
struct tnode *left;
struct tnode *right;
};
struct tnode *addtree(struct tnode *p, int d);
void treeprint(struct tnode *);
void freetree(struct tnode *p);
int main(void)
{
struct tnode *root;
int digit;
scanf("%d", &digit);
root = (struct tnode *) malloc(sizeof(struct tnode));
root->value = digit;
root->left = root->right = NULL;
while (scanf("%d", &digit) != EOF)
root = addtree(root, digit);
printf("中間順出力:n");
treeprint(root);
putchar('\n');
freetree(root);
return 0;
}
struct tnode *addtree(struct tnode *p, int d)
{
struct tnode *pp;
if(d != p->value){
pp = (struct tnode *) malloc(sizeof(struct tnode));
pp->value = d;
pp->left = pp->right = NULL;
}
else if(d == p->value)
return;
else if(d < p->value)
addtree(p->left, d);
else
addtree(p->right, d);
return pp->value;
}
void treeprint(struct tnode *p)
{
if ( p != NULL) {
treeprint(p->left);
printf("%4d", p->value);
treeprint(p->right);
}
}
void freetree(struct tnode *p)
{
if(p != NULL){
freetree(p->left);
freetree(p->right);
free(p);
}
}