哪位大牛帮我debug一个二叉树的程序,急啊,谢谢!
xjfox 2006-10-19 10:41:58 #include <stdio.h>
#include <malloc.h>
typedef struct treeNode
{
int key;
struct treeNode *Lchild;
struct treeNode *Rchild;
}treeNodeType;
treeNodeType *searchNode(treeNodeType *bn, int key)
{
if(bn == NULL)
return bn;
while(bn->key != key)
{
if(key < bn->key)
bn = bn->Lchild;
else
bn = bn->Rchild;
if(bn == NULL)
break;
}
return bn;
}
treeNodeType *insertNode(treeNodeType *bn, treeNodeType *cn, int key)
{
if(cn == NULL)
{
treeNodeType *cn = (treeNodeType *)malloc(sizeof(treeNodeType));
cn->Lchild = NULL;
cn->Rchild = NULL;
cn->key = key;
if(bn == NULL)
return cn;
if(key < bn->key)
bn->Lchild = cn;
else
bn->Rchild = cn;
}
if(key < cn->key)
insertNode(cn, cn->Lchild, key);
else if(key > cn->key)
insertNode(cn, cn->Rchild, key);
return bn;
}
void leverOrderPrintTree(treeNodeType *bn)
{
treeNodeType *queue[100];
int front, rear;
if(!bn)
return;
front = -1;
rear = 0;
queue[rear] = bn;
while(front != rear)
{
front++;
printf("%d ", queue[front]->key);
if(queue[front]->Lchild)
{
rear++;
queue[rear] = queue[front]->Lchild;
}
if(queue[front]->Rchild)
{
rear++;
queue[rear] = queue[front]->Rchild;
}
}
}
void main()
{
treeNodeType *bn;
int key;
bn = NULL;
while(1)
{
printf("Insert the key:\n");
scanf("%d", &key);
if(key == -1)
break;
bn = insertNode(bn, bn, key);
}
printf("Display the tree after insert:\n");
leverOrderPrintTree(bn);
}
当我输入第二个数时,在函数insertNode的
if(key < cn->key)
insertNode(cn, cn->Lchild, key);
else if(key > cn->key)
insertNode(cn, cn->Rchild, key);
会出错,而且错误不可见!