二叉排序树的查找,插入及创建(C++完整版)

#include<stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
#define maxSize 100
typedef struct BTNode
{
	int key;
	struct BTNode *lchild;
	struct BTNode *rchild;	
}BTNode;          // 二叉排序树的结构体 

BTNode* BSTSearch(BTNode *bt,int key)        //查找关键字并返回的是指针型 
{
	if(bt==NULL)
		return NULL;
	else
	{
		if(bt->key==key)
			return bt;
		else if(key<bt->key)
			return BSTSearch(bt->lchild,key);
		else
			return BSTSearch(bt->rchild,key); 
	} 
}
 
int BSTInsert(BTNode *&bt,int key)        //插入一个关键字 
{
	if(bt==NULL)
	 {
	 	bt=(BTNode*)malloc(sizeof(BTNode));
	 	bt->lchild=bt->rchild=NULL;
	 	bt->key=key;
	 	return 1;
	 }
	else
	{
		if(bt->key==key)
			return 0;
		else if(key<bt->key)
			return BSTInsert(bt->lchild,key);
		else
			return BSTInsert(bt->rchild,key); 
	} 
}
 
void CreateBST(BTNode *&bt,int n,int key[])   //创造二叉排序树 
{
	int i=0;
	for(i;i<n;i++)
		BSTInsert(bt,key[i]);
} 

void inorder(BTNode *bt)         //一个中序遍历判断是否构建完成 
{
	if(bt!=NULL)
	{
		inorder(bt->lchild);
		printf("%d ",bt->key);
		inorder(bt->rchild);
	}
}
int main(void)
{
	int key[ ]={1,2,3,4,5,6};
	int n=6;
	BTNode *bt;
	bt=(BTNode*)malloc(sizeof(BTNode));
	bt=NULL;					//突然发现把指针指向的地址置为空很重要,不然运行就出错了 
	CreateBST(bt,n,key);
//	BTNode *p=BSTSearch(bt,2);
//	cout<<p->key<<endl;
	BSTInsert(bt,7);
	inorder(bt);
	system("pause");
	return 0;
}
/*


*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值