c - 中序、先序和后序遍历

标签 c inorder preorder postorder

我编写了一个 C 程序来输入二叉搜索树的元素并显示其 InOrder、PostOrder 和 PreOrder 遍历。

#include<stdio.h>
#include<stdlib.h>
struct tnode
{
    int data;
    struct tnode *leftc;
    struct tnode *rightc;
};
int main()
{
    char ans='N';
    struct tnode *new_node,*root;
    //  struct tnode *get_node();
    root=NULL;
    do{
        // new_node=get_node();
        printf("\nEnter the Element");
        scanf("%d",&new_node->data);
        if(root==NULL)
            root=new_node;
        else
            insert(root,new_node);
        printf("\nDo you want to enter a new element?(y/n)");
        scanf("%c",&ans);
    }while(ans == 'y');
    printf("Inorder traversal:the elements in the tree are");
    inorder(root);
    printf("\nPreorder traversal:the elements in the tree are");
    preorder(root);
    printf("Postorder traversal:the elements in the tree are");
    postorder(root);
    return 0;
}
void insert(struct tnode ** tree,int num)
{
    struct tnode *temp = NULL;
    if(!(*tree))
    {
        temp=(struct tnode *)malloc(sizeof (struct tnode));
        temp->leftc=temp->rightc=NULL;
        temp->data=num;
        *tree=temp;
        return;
    }
    if(num < (*tree)->data)
    {
        insert(&(*tree)->leftc,num);
    }
    else if(num > (*tree)->data)
    {
        insert(&(*tree)->rightc,num);
    }
}
void preorder(struct tnode * s)
{
    if(s)
    {
        printf("%d\n",s->data);
        preorder(s->leftc);
        preorder(s->rightc);
    }
}
void inorder(struct tnode * s)
{
    if(s)
    {
        inorder(s->leftc);
        printf("%d\n",s->data);
        inorder(s->rightc);
    }
}
void postorder(struct tnode * s)
{
    if(s)
    {
        postorder(s->leftc);
        postorder(s->rightc);
        printf("%d\n",s->data);
    }
}

我收到这些警告消息:

warning: implicit declaration of functionS,
conflicting types OF FUNCTIONS,
new_node’ may be used uninitialized in this function

我不明白这些错误。你能帮我解决这些问题吗?

最佳答案

在 C 中,为了使用函数,您需要在 main 函数之前声明 em,就像您的情况一样,您应该这样写:

void insert(struct tnode ** tree,int num);
//all declarations of other functions here . 

//顺便说一句,你可以声明 em 而不用像这样的变量名称:

void insert(struct tnode ** , int );

也只是尝试在 C 中使用 google Binary Search Tree。 有许多网站可以准确显示您正在寻找的答案,还有许多网站提供的教程解释了它周围的一切。

附言 如果你不想在 main 函数之前声明函数,你可以把你已经准备好的函数放在 main 的上面,而 main 函数应该在最后的底部。

关于c - 中序、先序和后序遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38376343/

相关文章:

java - 中序二叉树方法的返回值

java - 将树遍历到数组中

c - ALSA:如何在设备列表中找到设备,但在打开它时仍然收到 "No such file or directory"?

c - 组成最小的数

c - 替换二进制文件中的字符串

java - 我的预购遍历出了什么问题?

python - 使用中序和先序遍历输出二叉树

使用 gdb 调试时的字符/字符串输入

c - 在C中递归地将InOrder二叉搜索树数据放入数组中

algorithm - 如何根据前序&中序或后序&中序遍历构建非二叉树?