二叉排序树的建立、查找、插入、删除

如题,详情见下代码,基本类似于二叉树。

#include<iostream> 
using namespace std;
struct node{
	int data;
	node *lchild,*rchild;
};

void search(node* root,int x) { // 查找 
	
	if(root==NULL){  //没有查到 
		printf("fail!\n");
		return;
	}
	if(root->data==x){ //查到 
		printf("succeed!");
		return;
	}
	if(root->data>x)search(root->lchild,x);
	else search(root->rchild,x);
}

void insert(node* &root,int x){ //插入 
//要改变指针地址,所以引用 
	if(root==NULL){
		root=new node;
		root->data=x;
		root->lchild=root->rchild=NULL; 
		return;
	}
	if(root->data>x)insert(root->lchild,x);
	else insert(root->rchild,x);
}

node* creating(int a[],int n){  //创建二叉树 
	node* root=NULL;
	for(int i=0;i<n;i++)
	insert(root,a[i]);
	return root;	
}

void del(node* &root,int x){   //删除值为x的结点 
	if(root==NULL)return;    //查找不到 
  if(root->data==x){//查找到了,如果前面的search改为node*型这里就简单 
		node *pre,*p;
		pre=root;
		if(root->lchild==NULL&&root->rchild==NULL){
		//如果这个结点是叶子结点 ,直接删 
		root=NULL;return;}
		if(root->lchild!=NULL){ //如果结点有左子树,找前驱 
			p=root->lchild;
			while(p->rchild){
				pre=p;
				p=p->rchild;	
			}
			p->rchild=root->rchild;  
			//前驱p代替root位置,其左子树放在父亲 pre的右子树上 
			pre->rchild=p->lchild;
			p->lchild=root->lchild;
			delete(root);return;	
		}
		else{                   //结点只有右子树,找后继 
			p=root->rchild;
			while(p->lchild){
				pre=p;
				p=p->lchild;	
			}
			p->rchild=root->rchild;
			//后继p代替root位置,其右子树放在父亲 pre的左子树上 
			pre->lchild=p->rchild;
			p->lchild=root->lchild;
			delete(root);return;	
		}
	}
    if(root->data>x) 
	del(root->lchild,x);
	else del(root->rchild,x);
	}

void preorder(node* root){  //先序遍历,用来检测下结果 
	if(root==NULL)return;
	printf("%d",root->data);
	preorder(root->lchild);
	preorder(root->rchild);
}

int main() {
	
	int a[]={4,1,2,8,7,9};
	node* root=creating(a,6);
	insert(root,3);
	del(root,9);
	preorder(root);
	return 0;
}
发布了63 篇原创文章 · 获赞 6 · 访问量 2022

猜你喜欢

转载自blog.csdn.net/qq_36684096/article/details/104608466