在C中实现二叉树

时间:2013-01-25 07:59:52

标签: c binary-tree

我正在尝试在C.中实现Binary树。首先插入值,然后将它们遍历到Preorder.But,当我调用函数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()中进行更正..它可以是什么?

3 个答案:

答案 0 :(得分:3)

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

 while(root!=NULL){

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

答案 1 :(得分:2)

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

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

在循环体中,您不会在任何点更改根指针,因此,如果条件为真,则它是根元素,它将永远不会退出循环。

应该是:

if(root!=NULL){

答案 2 :(得分:0)

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

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

相关问题