Распечатать двоичное дерево в алфавитном порядке - PullRequest
0 голосов
/ 04 мая 2020

Мне нужно распечатать двоичное дерево от самого нижнего левого узла до самого нижнего правого узла, причем дерево сортируется в алфавитном порядке.

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");
}}

1 Ответ

0 голосов
/ 04 мая 2020

Это может быть ваша функция печати:

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

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

    if (root->right)
        print(root->right);
}
...