[英]Binary Search Tree insertion/traversal not functioning properly
I'm trying to implement BST by inserting a few elements (5,8,10,20,30), and printing them by inorder traversal.我试图通过插入一些元素(5、8、10、20、30)来实现 BST,并通过中序遍历打印它们。 But the output is:但是 output 是:
5 8 30 20 8 30 10 5 8 30 20 8 30
instead of:代替:
5 8 10 20 30
I tried to debug the code, but it seems to malfunction at the inorder traversal part even though it's correct(in my opinion).我试图调试代码,但它似乎在中序遍历部分出现故障,即使它是正确的(在我看来)。
Here's the code:这是代码:
#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;
}
Change改变
if(key<tail->data)
tail->lchild=new;
tail->rchild=new;
To至
if (key<tail->data) tail->lchild=new;
else tail->rchild=new;
The joy of pointer-to-pointer:指针对指针的乐趣:
void insert(int key)
{
struct tree **pp, *new;
for ( pp = &root; *pp ; ) {
if (key < (*pp)->data)
pp = &(*pp)->lchild;
else if (key > (*pp)->data)
pp = &(*pp)->rchild;
else return;
}
new = malloc(sizeof *new );
new->data = key;
new->lchild = new->rchild = NULL;
*pp = new;
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.