因此,我try 使用给定的数组创建一棵二叉树,然后按顺序、预排序和后序打印结果,但似乎我在某个地方做错了,但据我所知,事情应该没有问题.

这是它打印出来的结果

1 2 3 4 5 6 7 8 9 10  #inorder
10 9 8 7 6 5 4 3 2 1  #postorder
1 2 3 4 5 6 7 8 9 10  #preorder

这就是我到目前为止所做的.有没有人能指出这个错误,或许还能给出一个如何改正的建议?

#include <stdio.h>
#include <stdlib.h>

typedef struct node_s node_t;
struct node_s
{
    int key;
    node_t *left,*right;
};
node_t *new_node(int val)
{
    node_t *new;
    new= malloc(sizeof (node_t));
    if(new==NULL)
    {
        exit(1);
    }
    new->key=val;
    new->left=NULL;
    new->right=NULL;
    return new;
}
void print_inorder(node_t *root)
{
    node_t *new=root;
    if (new != NULL) {
        print_inorder(new->left);
        printf("%d ",new->key);
        print_inorder(new->right);
    }
    return;

}
void print_postorder(node_t *root)
{
    node_t *new=root;
    if (new != NULL) {
        print_postorder(new->left);
        print_postorder(new->right);
        printf("%d ",new->key);
    }
    return;

}
void print_preorder(node_t *root)
{
    node_t *new=root;
    if (new != NULL) {
        printf("%d ",new->key);
        print_preorder(new->left);
        print_preorder(new->right);
    }
    return;

}
node_t *insert_node(node_t *root,int val)
{
     if(root==NULL)
            return new_node(val);
     else
     {
         if(val<root->left)
             root->left= insert_node(root->left,val);
         else if(val>root->left)
             root->right= insert_node(root->right,val);
     }
    return root;
}
int main() {

    int n;
    int v[]={1,2,3,4,5,6,7,8,9,10};
    node_t *root=NULL;
    FILE *file;
    file= fopen("file","r");
    if(file==NULL)
    {
        exit(1);
    }
    for (int i = 0; i < 10; ++i) {
        root= insert_node(root,v[i]);
    }

    print_inorder(root);
    printf("\n");
    print_postorder(root);
    printf("\n");
    print_preorder(root);

    return 0;
}

推荐答案

省点时间,enable all compiler warnings.

Problems identified in seconds!
Code has at least this problem:

Compare between integer and pointer

// warning: comparison between pointer and integer
if (val < root->left) // Bad

可能被通缉:

if (val < root->key)

else if (val > root->left)个也是如此

C++相关问答推荐

从内联程序集调用Rust函数和调用约定

单指针和空参数列表之间的函数指针兼容性

有没有更简单的方法从用户那里获取数据类型来计算结果

为什么STM32G474RE上没有启用RCC PLL

CC2538裸机项目编译但不起作用

防止规范模式在C++中 echo 特殊字符

在WSL关闭/重新启动后,是什么原因导致共享对象依赖关系发生更改?

CGO:如何防止在使用CGO在包中包含C头文件时出现多个定义...&q;错误?

我的C函数起作用了,但我不确定为什么

使用nmake for程序比Hello World稍微复杂一些

使用ld将目标文件链接到C标准库

Go和C中的数据 struct 对齐差异

为什么WcrTomb只支持ASCII?

我可以创建适用于不同endian的 colored颜色 struct 吗?

生成一个半RNG,结果用C表示(无随机/随机)

当我在34mb的.mp4文件中使用FREAD时,我得到了一个分段错误,我如何解决它?

哪些C++功能可以在外部C块中使用

为什么孤儿进程在 Linux 中没有被 PID 1 采用,就像我读过的一本书中声称的那样?

为什么<到达*时不会转换为>?

无法在线程内用 C 打印?