#include<bits/stdc++.h>
struct node{
int data;
node* lchild;
node* rchild;
};
void search(node* root,int x){//查找二叉查找树中数据域为x的结点
if(root==NULL){
printf("search failed\n");
return;
}
if(x==root->data){//查找成功,访问之
printf("%d\n",root->data);
}
else if(x<root->data){//如果x比根节点的数据域小,说明x在左子树
search(root->lchild,x);//向左子树搜索x
}else{//x比根节点的数据域大,说明x在右子树
search(root->rchild,x);//向右子树搜索x
}
}
node* newNode(int v){//生成一个新结点,x为结点权值
node* Node=new node;//申请一个node型变量的地址空间
Node->data=v;
Node->lchild=Node->rchild=NULL;//初始状态下没有左右孩子
return Node;//返回新建结点的地址
}
void insert(node* &root,int x){//在二叉树中插入一个数据域为x的新结点
if(root==NULL){//空树,说明查找失败,也即插入位置
root=newNode(x);//新建结点,权值为x
return;
}
if(x==root->data) return;
else if(x<root->data){//x比根节点的数据域小时需要插在左子树
insert(root->lchild,x);//往左子树搜索x
}else{//x比根节点的数据域大时需要插在右子树
insert(root->rchild,x);//往右子树搜索x
}
}
node* Create(int data[],int n){
node* root=NULL;//新建根节点root
for(int i=0;i<n;i++){
insert(root,data[i]);
}
return root;//返回根节点
}
node* findMax(node* root){
while(root->rchild!=NULL) root=root->rchild;//不断往右,直到没有右孩子
return root;
}
node* findMin(node* root){
while(root->lchild!=NULL) root=root->lchild;//不断往左,直到没有左孩子
return root;
}
void deleteNode(node* &root,int x){//删除以root为根节点的树种权值为x的结点
if(root==NULL) return;//不存在权值为x的结点
if(root->data==x){//找到欲删除的结点
if(root->lchild==NULL&&root->rchild==NULL){//叶子结点直接删除
root=NULL;
}
else if(root->lchild!=NULL){//左子树不为空时
node* pre=findMax(root->lchild);//找root的前驱
root->data=pre->data;
deleteNode(root->lchild,pre->data);//在左子树种删除结点pre
}
else if(root->rchild!=NULL){
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);
}
}
二叉查找树的基本操作
最新推荐文章于 2023-04-17 20:36:56 发布