按字母顺序打印二进制树。

问题描述 投票:0回答:1

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

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 exists\n");
}}
c binary-tree
1个回答
0
投票

这可能是你的打印函数。

void print(struct Book *root) {
    if (root->left)
        print(root->left);

    printf("%s\n", root->title);

    if (root->right)
        print(root->right);
}
© www.soinside.com 2019 - 2024. All rights reserved.