出现的问题莫名其妙#include#includetypedefintKeyType;typedefstructnode{KeyTypekey;structnode*lchild,*rchild;}BSTNode;typedefBSTNode*BSTree;//二叉排序树插...出现的问题莫名其妙
#include
#include
typedef int KeyType;
typedef struct node
{
KeyType key;
struct node *lchild,*rchild;
} BSTNode;
typedef BSTNode *BSTree;
//二叉排序树插入
//若二叉排序树 *Tptr中没有关键字为key,则插入二叉排序树的实现,否则直接返回
void InsertBST( BSTree *TPtr , KeyType key )
{
BSTNode *f , *p;
p = *TPtr; //p的初值指向根节点
while(p) //查找插入位置
{
if( p->key == key ) //树中已有key,无须插入
{
return;
}
f=p; //f保存当前查找的节点
//若keykey,则在左子树中查找,否则在右子树中查找
p=(keykey)? p->lchild:p->rchild;
}
p=(BSTNode *)malloc( sizeof(BSTNode) );
p->key=key;
p->lchild=p->rchild=NULL;//生成新结点
if(*TPtr==NULL) //原树为空
{
*TPtr=p; //新插入的节点为新的根
}
else //原树非空时将新节点p作为f的左孩子或右孩子插入
{
if(keykey)
{
f->lchild=p;
}
else
{
f->rchild=p;
}
}
//创建二叉排序树
//输入一个结点序列二叉排序树的实现,建立一棵二叉排序树,将根节点指针返回
BSTree CreateBST( void )
{
BSTree T=NULL;
KeyType key;
scanf( "%d" , &key );
while(key) //假设key=0是输人结束标志
{
InsertBST( &T , key );//将key插入二叉排序树T
scanf( "%d" , &key );//读人下一关键字
}
return T;
}
//查找二叉排序树 T 中是否存在指定的 key
//指针 f 指向 T 的双亲, f 初始值为 NULL
//若查找成功返回1,指针p指向该数据元素节点,否则返回0,p指向查找过程中的最后一个结点
int SearchBST( BSTree T , int key , BSTree f , BSTree *p)
{
if( !T )
{
*p = f;
return 0;
}
else if( T->key == key )
{
*p = T;
return 1;
}
else if( T->key > key )
{
return SearchBST( T->lchild , key , T , p );
}
else
{
return SearchBST( T->rchild , key , T , p );
}
}
//访问节点数据
void visit( KeyType c , int level )
{
printf( "%d 在第 %d 层\n" ,c , level );
}
//前序遍历树节点
void PreorderTraverse( BSTree T ,int level )
{
if(T)
{
visit(T->key , level );
PreorderTraverse(T->lchild , level+1 );
PreorderTraverse(T->rchild , level+1 );
}
}
int main()
{
int level=1;
BSTree T;
T = CreatBST();
PreorderTraverse( T , level );
return 0;
}
求指点代码在何处为何出错
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-129912-1.html