c-按字母顺序打印二进制树



我需要打印出一个从最左下角节点到最右下角节点的二进制树,树按字母顺序排序。

struct Book{
/* Book details */
char title[MAX_TITLE_LENGTH+1];   /* name string */
char author[MAX_AUTHOR_LENGTH+1]; /* job string */
int  year;                        /* year of publication */
/* pointers to left and right branches pointing down to next level in
the binary tree (for if you use a binary tree instead of an array) */
struct Book *left, *right;};

我写了一个比较函数,可以按字母顺序将书籍添加到树中,但我不知道如何修改它以按字母顺序打印。

void compare(struct Book *a, struct Book* new){
struct Book *temp; temp =(struct Book *)malloc(sizeof(struct Book));
if(strcmp(a->title, new->title)<0){
if(a->right == NULL)
a->right = new;
else{
temp = a->right;
compare(temp,new);
}
}
else if(strcmp(a->title, new->title)>0){
if(a->left == NULL)
a->left = new;
else{
temp = a->left;
compare(temp,new);
}
}
else if(strcmp(a->title, new->title) == 0){
fprintf(stderr, "nThis title already existsn");
}}

这可能是您的打印功能:

void print(struct Book *root) {
if (root->left)
print(root->left);
printf("%sn", root->title);
if (root->right)
print(root->right);
}

最新更新