按字母顺序打印二叉树
Print a Binary tree in alphabetical order
我需要从最左下角的节点到最右下角的节点打印一棵二叉树,树按字母顺序排序。
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");
}}
这可能是您的打印功能:
void print(struct Book *root) {
if (root->left)
print(root->left);
printf("%s\n", root->title);
if (root->right)
print(root->right);
}
我需要从最左下角的节点到最右下角的节点打印一棵二叉树,树按字母顺序排序。
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");
}}
这可能是您的打印功能:
void print(struct Book *root) {
if (root->left)
print(root->left);
printf("%s\n", root->title);
if (root->right)
print(root->right);
}