c - 用 C 实现二叉树

标签 c binary-tree

我正在尝试在 C 中实现二叉树。首先插入值,然后将它们遍历到 Preorder 中。但是当我调用函数 preorder() 时,它会给我无限循环,仅插入最后一个值。 我正在使用以下代码:

struct node* insert(struct node *root,int num);

void preorder(struct node *root);

struct node *root=NULL;

int count=1;

struct node {

    struct node *lchild;
    struct node *rchild; 
int data;
};

int main(){

    root=insert(root,1);
//root=insert(root,2);
preorder(root); 
return;
}

struct node* insert(struct node *root,int num){//insert a node into tree

   //struct node *q;
if(root==NULL)
{
    root=(struct node*)malloc(sizeof(struct node)); 
    root->data=num;
    root->lchild=NULL;
    root->rchild=NULL;
    //root=q;
    count++;
}
else{
    if(count % 2==0){
        root->lchild=insert(root->lchild,num);
    }
    else{
        root->rchild=insert(root->rchild,num);
    }
}
return(root);
}

void preorder(struct node *root){

    while(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->lchild);
    preorder(root->rchild);     
}
}

这里我最初只插入1个值,但出现了错误。所以在insert()中不应该有任何错误,应该在preorder()或main()中进行一些修正..它可能是什么?

最佳答案

我不确定 preorder() 应该做什么,但是这一行会导致无限循环:

 while(root!=NULL){

我猜你的意思是写if而不是while

关于c - 用 C 实现二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14517662/

相关文章:

转换字符和 fgets() 函数未按预期工作

python - 二叉树的并行编程

c - 在C中将数学方程插入二叉树

c - 在 .c 文件中包含守卫的目的

sql - 快速构建源自 SQL 数据库的 Web 图表原型(prototype)的方法

关于 x86_64 Linux 上堆栈增长的困惑

c++ - 在二叉树中找到最大的字典序根到叶路径

java - path.remove,二叉树路径总和

仅给出后序构造完整二叉树?

c - 循环直到找到特定字符串