私はツリーをC言語で実装しようとしていますが、トラバースしようとするたびにツリーの最初の3つのノードしか表示されず残りは失われます。私が100,200,300,400,500,600,700と入力すると、100,200,300が出力されます。私は問題がの挿入機能であると思うが、私はそれを把握できない。Cのバイナリツリーの実装
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
typedef struct node list;
list *head, *tail, *current, *newn;
void inorder(struct node *t)
{
if(t != NULL)
{
inorder(t->prev);
printf("%d->",t->data);
inorder(t->next);
}
}
struct node * insert(int key, struct node *t)
{
if(t == NULL)
{
t = (list*)malloc(sizeof(list));
t->data = key;
t->prev = NULL;
t->next = NULL;
}
else if(t->prev == NULL)
{
t->prev = insert(key,t->prev);
}
else if(t->next == NULL)
{
t->next = insert(key,t->next);
}
return(t);
}
int main()
{
int x=1, y, z=1;
current = (list*)malloc(sizeof(list));
printf("Enter data:");
scanf("%d",¤t->data);
current->next = NULL;
current->prev = NULL;
head = current;
while(z == 1)
{
printf("Enter data:");
scanf("%d",&y);
current = insert(y,current);
printf("want to insert more:");
scanf("%d",&z);
}
printf("\nInorder Traversal:");
newn = head;
inorder(newn);
}
Scanf(特に戻り値をチェックしない)は危険です(http://sekrit.de/webdocs/c/beginners-guideaway-from-scanf.html)。 scanfを使用する代わりに、10個のノード値をハードコードすることで実験を試してみてください。それ以外の場合(@ lurkerに同意する)https://ericlippert.com/2014/03/05/how-to-debug-small-programs/およびhttps://stackoverflow.com/questions/2069367/how-to-debug- using-gdb – Yunnosch
'root'が2つの非' NULL'子要素を持つ場合、 'insert'は追加されません。 – BLUEPIXY
@BLUEPIXYどうすればいいですか? – TrustTyler