【问题标题】:Print a Binary tree in alphabetical order按字母顺序打印二叉树
【发布时间】:2020-08-18 23:28:13
【问题描述】:

我需要从最左下角的节点到最右下角的节点打印一棵二叉树,并按字母顺序排序。

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

【问题讨论】:

  • 您不必为了打印而修改插入代码。正确插入可确保左节点比右节点“小”。只需按顺序走树即可。所有的字符串比较都在插入中,因此打印可以依赖正确的顺序。
  • 如果树已经排好序了,为什么还要触摸compare函数呢?相反,您需要提供类似traverse 的函数。
  • 我还建议在比较函数“int comparison = strcmp(a->title, new->title);”之上添加这个以及在所有 ifs 中使用“比较”。您也不必强制转换 malloc。
  • 感谢您的想法。我已经成功了:)

标签: c binary-tree


【解决方案1】:

这可能是您的打印功能:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多