二叉排序树的实现c语言,二叉排序树的C语言实现

093527xan8jyy4f78rnf0a.jpg

出现的问题莫名其妙#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;

dfcfe286960feb75473718c0b6628121.png

}

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;

19f5823a8e6fc02d843740ba8fd2f80e.png

}

}

//创建二叉排序树

//输入一个结点序列二叉排序树的实现,建立一棵二叉排序树,将根节点指针返回

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)

{

d37db08a03ba1a98d2c67b8f0653a2cf.png

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 )

ecb23e083463059a548f9834e9153967.png

{

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值