1
我想在C中實現一個Binary Tree數據結構,並在幾次插入後執行一次inorder遍歷。 程序只打印我插入的第一個元素,而不打印其他任何節點。二叉樹InOrderWalk實現不按預期方式工作
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct tree
{
struct node *root;
};
struct node
{
int val;
struct node *left;
struct node *right;
};
struct tree *init()
{
struct tree *t = malloc (sizeof (struct tree));
t->root = NULL;
return t;
}
void insert (struct tree *t, int val)
{
struct node *succ;
struct node *new = malloc (sizeof (struct node));
new->val = val;
new->left = NULL;
new->right = NULL;
succ = NULL;
struct node *insertPlace = t->root;
while (insertPlace != NULL)
{
succ = insertPlace;
if (insertPlace->val < new->val)
insertPlace = insertPlace->right;
else
insertPlace = insertPlace->left;
}
if (succ == NULL)
t->root = new;
else if (new->val < succ->val)
insertPlace = succ->right;
else
insertPlace = succ->left;
}
void inorderWalk (struct node *p)
{
if (p != NULL)
{
if (p->left != NULL)
inorderWalk (p->left);
printf ("%d ", p->val);
if (p->right != NULL)
inorderWalk (p->right);
}
}
void
print (struct tree *t)
{
struct node *p;
p = t->root;
inorderWalk (p);
}
int
main()
{
struct tree *t = init();
insert (t, 5);
insert (t, 15);
insert (t, 20);
insert (t, 1);
insert (t, 2);
insert (t, 4);
insert (t, 10);
print (t);
return 0;
}
該代碼也可用here與在線gdb調試器。
關於爲什麼代碼不能按預期工作的任何反饋將非常感激。
非常感謝您的幫助。
這工作就像一個魅力!現在節點被正確插入並按正確的順序遍歷。非常感謝,保羅! –