二叉排序树的创建、查找、节点删除、中序遍历(完整代码)

要注意的是删除节点的那一部分代码(用前驱或后继替代),结合理论知识来记忆
代码:

#include <stdio.h>
#include <queue>
using namespace std;

struct node{
	int data;
	node* lchild;
	node* rchild;
};
node* root = NULL;
//新建一个节点
node* newNode(int v){
	node* Node = new node;
	Node->data = v;
	Node->lchild = NULL;
	Node->rchild = NULL;
	return Node;
} 


//找到二叉查找树中数据域为x的节点 
void search(node* root,int x){
	if(root == NULL){
		printf("search failed\n");
		return;
	}
	if(x == root->data){
		printf("%d\n",root->data);
	}
	else if(x <root->data){
		search(root->lchild,x);
	}
	else{
		search(root->rchild,x);
	}
}
//中序遍历
void inorder(node* root){
	if(root == NULL){
		return;
	}
	inorder(root->lchild);
	printf("%d ",root->data);
	inorder(root->rchild);
}
 
//insert函数将在二叉树中插入一个数据域为x的新节点
void insert(node* &root,int x){
	if(root == NULL){
		root = newNode(x);//如果节点不存在,新增一个 
		return;
	}
	if(x == root->data){//已经存在就返回 
		return;
	}
	else if(x <root->data){
		insert(root->lchild,x);
	}
	else{
		insert(root->rchild,x);
	}
}
//二叉树的建立
node* Creat(int data[],int n){
	node* root = NULL;
	for(int i = 0;i <n;i++){
		insert(root,data[i]);
	}
	return root;
} 

//寻找以root为根节点的树中的最大权值节点
node* findMax(node* root){
	while(root->rchild != NULL){
		root= root->rchild;//直到没有右孩子 
	}
	printf("最大权值节点的数据为%d\n",root->data);
	return root;
} 
//寻找以root为根节点的树中的最小权值
node* findMin(node* root){
	while(root->lchild != NULL){
		root = root->lchild;
	}
	printf("最小权值节点的数据为%d\n",root->data);
	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;
		}
		else if(root->lchild != NULL){//左子树不为空时 
			node* pre = findMax(root->lchild);
			root->data = pre->data;
			deleteNode(root->lchild,pre->data);
		}
		else{//右子树不为空时 
			node* next = findMin(root->rchild);
			root->data = next->data;
			deleteNode(root->rchild,next->data);
		}
	}
	else if(root->data>x){//节点数据比x大,前往左子树删除 
		deleteNode(root->lchild,x);
	}
	else{//节点数据比x小,前往右子树删除 
		deleteNode(root->rchild,x);
	}
}

int main(){
	int data[10] = {1,3,5,7,9,2,4,6,8,10};
	node* linshi = Creat(data,10);
	findMax(linshi);
	findMin(linshi);
	printf("中序遍历输出数据为:\n");
	inorder(linshi);
	deleteNode(linshi,4);
	printf("\n删除4后,中序遍历输出数据为:\n"); 
	inorder(linshi);	
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值