【发布时间】:2020-07-04 14:04:18
【问题描述】:
我试图通过插入一些元素 (5,8,10,20,30) 来实现 BST,并通过中序遍历打印它们。但输出是:
5 8 30 20 8 30 10 5 8 30 20 8 30
代替:
5 8 10 20 30
我尝试调试代码,但它似乎在中序遍历部分出现故障,即使它是正确的(在我看来)。
代码如下:
#include<stdio.h>
#include<stdlib.h>
struct tree{
struct tree *lchild, *rchild;
int data;
}*root=NULL;
void insert(int key)
{
struct tree *tail,*new,*temp=root;
if(root==NULL)
{
new=(struct tree*)malloc(sizeof(struct tree));
new->data=key;
new->lchild=new->rchild=NULL;
root=new;
return;
}
else{
while(temp!=NULL)
{
tail=temp;
if(key<temp->data)
temp=temp->lchild;
else if(key>temp->data)
temp=temp->rchild;
else
return;
}
new=(struct tree*)malloc(sizeof(struct tree));
new->data=key;
new->lchild=new->rchild=NULL;
if(key<tail->data)
tail->lchild=new;
tail->rchild=new;
}
}
void inOrder(struct tree *temp)
{
if(temp)
{
inOrder(temp->lchild);
printf("%d ",temp->data);
inOrder(temp->rchild);
}
}
int main()
{
insert(10);
insert(5);
insert(20);
insert(8);
insert(30);
inOrder(root);
return 0;
}
【问题讨论】:
-
将您的代码与here显示的代码进行比较。
-
是的,我之前浏览过这段代码。它使用递归函数进行插入。我正在使用迭代函数。除此之外,代码中几乎所有其他内容都相同。
-
tail->rchild=new;--->>else tail->rchild=new;
标签: c binary-tree binary-search-tree