9.4 二叉查找树基础算法

#include <cstdio>
#include <queue>
using namespace std;
struct node{
	typename data;
	node* lchild;
	node* rchild;
};
node *root=NULL;

//1建立新结点,v为结点权值
node * newnode(int v)
{
	node *Node =new node; //申请一个node型变量的地址空间
	Node ->data=v; //结点权值为v 
	Node->lchild=Node->rchild=NULL; //初始状态下没有左右孩子 
	return Node; //返回新建结点的地址 
}
//二叉查找树
//1、查找 
void search(node*root,int x)
{
	if(root==NULL)
	{
		printf("search failed\n");
		return ;
	}
	if(root->data==x) //查找成功,访问之 
		printf("%d\n",root->data);
	else if(root->data<x) //x比根节点的数据域小,说明x在左子树 
		search(root->lchild,x);//递归往左子树搜索 
	else //x大于根结点的数据域 
		search(root->rchild,x); //递归搜索右子树 
 } 
//2、插入
void insert(node*root,int x)
{
	if(root==NULL)//空树,查找失败,也即插入位置 
	{
		root =newnode(x); //新建结点,权值为x;见9.1.3
		return; 
	}
	if(x==root->data)//查找成功,结点已经存在,返回 
		return;
	else if(x<root->data)
		insert(root->lchild,x);//x比根节点数据域小,需要插在左子树 
	else
		insert(root->rchild,x); //x大于根节点,插入右子树 
}
//3、二叉查找树的建立
node * create(int data[],int n)
{
	node* root=NUll;//新建根结点
	for(int i=0;i<n;++i)
	{
		insert(root,data[i]);
	} 
	return root;
}

//4、二叉查找树的删除
//4.1寻找以root为根节点的树中的最大权值结点
node *findmax(node *root)
{
	while(root->rchild!=NULL)
	{
		root=root->rchild;//不断往右,直到没有右孩子 
	}
	return root; 
}
//4.2 寻找以root为根节点的树中的最小权值结点
node *findmin(node*root)
{
	while(root->lchild!=NULL)
		root=root->lchild;
	return root;
}

//删除以root为根结点的树中权值为x的结点
void deletenode(node *&root,int x) 
{
	if(root==NULL)
		return;
	if(root->data==x) //找到欲删除的结点 
	{
		if(root->lchild==NULL&&root->rchild==NULL) //叶结点,直接删除 
			root=NULL; //把root地址设为NULL,父节点就引用不到它了 
			//free(root);
		else if(root->lchild!=NULL) //左子树不空 
		{
			node* pre=findmax(root->lchild); //找root的前驱
			root->data=pre->data;//用前驱结点的数据域覆盖root
			deletenode(root->lchild,pre->data);//往左子树中删除结点pre 
		}
		else //右子树不空 
		{
			node* next=findmin(root->rchild);//找root后继
			root ->data=next->data;//用后继覆盖root 
			deletenode(root->rchild,next->data);//往右子树中删除结点next 
		}  
	}
	else if(root->data>x)
		deletenode(root->lchild,x);//往左子树递归删除x 
	else 
		deletenode(root->rchild,x); 
 } 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值