#include<iostream>
using namespace std;
class tree{
public:
class node{
public:
int value;
char key;
node* left;
node* right;
node(int v,char k){
this->value=v;
this->key=k;
}
};
node* root;
tree::node* insert(node* root,int v,char);
tree::node* createTree();
char find(node* root,int key);
tree::node* tree::getMinNode(node* n);
tree::node* tree::delMin(node* n);
tree::node* tree::remove(node* root,int key);
void tree::midShow(node* root);
};
tree::node* tree::createTree(){
node* n=insert(NULL,5,'h');
n=insert(n,3,'a');
insert(n,8,'b');
insert(n,2,'c');
insert(n,1,'d');
insert(n,6,'e');
insert(n,9,'f');
insert(n,4,'g');
return n;
}
tree::node* tree::insert(node* root,int v,char k){//出现错误,未连接子树,root->right=insert(root->right,v,k);
//注意return,可以直接return本层,也可以接受递归层的return值。
if(root==NULL){
root=new node(v,k);
root->left=NULL;
root->right=NULL;
cout<<"插入成功"<<":"<<root->value<<endl;
}else if(v==root->value){
cout<<"有同"<<endl;
}else if(v>root->value){
root->right=insert(root->right,v,k);
}else if(v<root->value){
root->left=insert(root->left,v,k);
}
return root;
}
char tree::find(node* root,int key){
if(root!=NULL){
if(key==root->value){
return root->key;
}else if(key>root->value){
return find(root->right,key);
}else{
return find(root->left,key);
}
}
return 'r';
}
//删除
tree::node* tree::getMinNode(node* n){
if(n->left!=NULL){
return getMinNode(n->left);
}
return n;
}
tree::node* tree::delMin(node* n){
if(n!=NULL){
if(n->left==NULL){
return n->right;
}
n->left=delMin(n->left);
}
return n;
}
tree::node* tree::remove(node* root,int key){//函数的参数int key与root->value对应
if(root!=NULL){
if(key<root->value){
root->left=remove(root->left,key);
}else if(key>root->value){
root->right=remove(root->right,key);//只返回到上一层就断了。
}else{
if(root->left==NULL){
return root->right;
}else if(root->right==NULL){
return root->left;
}else{
node* n=root;
root=getMinNode(n->right);//这里root已是另一指针了,而n指向原来root的指针。
root->right=delMin(n->right);
root->left=n->left;
}
}
}
return root;
}
void tree::midShow(node* root){
if(root!=NULL){
midShow(root->left);
cout<<root->value<<" ";
midShow(root->right);
}
}
int main(){
tree *t=new tree();
t->root=t->createTree();
//中序遍历结果为从小到大顺序
cout<<"中序遍历:";
t->midShow(t->root);
cout<<endl;
//输出key=8的value
char r=t->find(t->root,8);
cout<<r<<endl;
//"删除key=8的节点
cout<<"删除key=8的节点"<<endl;
t->remove(t->root,8);
r=t->find(t->root,8);
cout<<r<<endl;
cout<<"中序遍历:";
t->midShow(t->root);
cout<<endl;
return 0;
}
二叉搜索树
最新推荐文章于 2024-09-16 23:33:58 发布