#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;
}
下面是删除操作参考图