我正在尝试在 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/