c++对树的简单实现

#include<iostream>
#include<queue>
#include<stack>
using namespace std;
class poinner{//树 
	public:
	int val;
	poinner*right,*left;
	poinner(int val){
		this->val=val;
		right=nullptr;
		left=nullptr;
	}
};
poinner* create(int val){//初始化 
	poinner* root=new poinner(val);
	return root;
}
void insert(poinner*&root,const int val){//插入 
	if(!root){
		root=create(val);
	}else if(val<root->val){
		insert(root->left,val);
	}else if(val>root->val){
		insert(root->right,val);
	}else{
		//数据相同则不执行操作
	}
}
void d_prin1(poinner*root){//深度优先-先序 
	if(!root)return;
	else{
		cout<<root->val<<" ";
		d_prin1(root->left);
		d_prin1(root->right);
	}
}
void d_prin2(poinner*root){//深度优先-中序 
	if(!root)return;
	else{
		
		d_prin2(root->left);
		cout<<root->val<<" ";
		d_prin2(root->right);
		
	}
}
void d_prin3(poinner*root){//深度优先-后序 
	if(!root)return;
	else{
		d_prin3(root->left);
		d_prin3(root->right);
		cout<<root->val<<" ";
	}
}
void b_prin(poinner*root){//广度优先 
	poinner*p=root;
	queue<poinner*>q;
	q.push(p);
	while(!q.empty()){
		p=q.front();
		if(p){
			cout<<p->val<<" ";
		q.push(p->left);
		q.push(p->right);
		}
			q.pop();
	}

}
poinner* select(poinner*root,int val){//查找指定值 
	if(root==nullptr||root->val==val){
		return root;
	}
	if(val<root->val){
		select(root->left,val);
	}
	if(val>root->val){
		select(root->right,val);
	}
}

poinner* max(poinner*root){//查找最大 
	while(root->right)root=root->right;
	return root;
}
poinner* min(poinner*root){//查找最小 
	while(root->left)root=root->left;
	return root;
}
poinner* deletepoin(poinner*root,int val){//删除 
	if(!root){
	}
	else if(val<root->val){
		root->left=deletepoin(root->left,val);
	}else if(val>root->val){
		root->right=deletepoin(root->right,val);
	}else{
		if(root->left&&root->right){
			poinner* tem=min(root->right);
			root->val=tem->val;
			root->right=deletepoin(root->right,tem->val);
		}else{
			poinner* tem=root;
			if(!root->left){
				root=root->right;
			}else if(!root->right){
				root=root->left;
			}
			delete(tem);
		}
	}
		return root;
}
int main(){
	poinner*head=create(5);
	poinner*ans=head;
	insert(head,4);
	insert(head,6);
	insert(head,3);
	insert(head,2);
	insert(head,7); 
	head=deletepoin(head,7); 
	b_prin(head);
	return 0;
}

下面是删除操作参考图
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值