繁体   English   中英

在C中实现二叉树

[英]Implementing the Binary Tree in C

我正在尝试在C中实现Binary树,首先插入值然后将它们遍历到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){

我猜你的意思是写ifwhile

您需要在预订函数中使用if语句而不是while语句。

while(root!=NULL){ //This is causing the infinite loop

在循环体中,您不会在任何时候更改根指针,因此,如果条件一直为真(对于根元素而言),则永远不会退出循环。

相反,它应该是:

if(root!=NULL){

您必须编写if而不是while以便递归循环具有基本条件并在某处结束。

在您的代码中而不是if(root!=NULL)编写while(root!=NULL)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM