这是从算法第四版上改过来的,
之后还会补充一点,先把这些当上来吧
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<windows.h>
#include<vector>
#include<stack>
#include<queue>
#include<cstring>
#include<string>
#include<unordered_map>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
typedef struct BSTNode{
char key;
int value;
BSTNode*left,*right;
int N;
BSTNode():left(NULL),right(NULL){}
BSTNode(char k,int value,int N,BSTNode*l=NULL,BSTNode*r=NULL):key(k),value(value),N(N),left(l),right(r){}
}BSTNode;
typedef struct BST{
public:
BSTNode*root;
int compare(char a,char b)
{
if(a>b)return 1;
else if(a<b)return -1;
else return 0;
}
int size(BSTNode*x)
{
if(x==NULL)return 0;
else return x->N;
}
void put(char k,int v){root=put(root,k,v);}
//error!
BSTNode* put(BSTNode*x,char k,int v)
{
if(x==NULL)return new BSTNode(k,v,1);
cout<<"k "<<k<<" x->key "<<x->key<<endl;
int cmp=compare(k,x->key);
cout<<"cmp"<<cmp<<endl;
if(cmp>0)x->right=put(x->right,k,v);
else if(cmp<0)x->left=put(x->left,k,v);
else x->value=v;
x->N=size(x->left)+size(x->right)+1;
return x;
}
//迭代形式的查找
void find(char key)
{
int x;
if(find(root,key,x))printf("FIND! %d\n",x);
else printf("FAILED NO MATCHED!\n");
}
bool find(BSTNode*root,char key,int&x)
{
if(root==NULL)return 0;
bool flag=0;
BSTNode*temp=root;
while(temp!=NULL)
{
if(key>temp->key)temp=temp->right;
else if(key<temp->key)temp=temp->left;
else {flag=1;x=temp->value;break;}
}
return (flag==1)?1:0;
}
void preorder(){preorder(root);}
void preorder(BSTNode*root)
{
if(root==nullptr)return;
cout<<root->key;
preorder(root->left);
preorder(root->right);
}
//中序遍历BST
//得到一个顺序的,时间复杂度和快速排序相近
//o(logn)
void inorder(){inorder(root);}
void inorder(BSTNode*root)
{
if(root==nullptr)return;
inorder(root->left);
cout<<root->key;
inorder(root->right);
}
void build()
{
vector<char>keyary{'s','e','x','a','c','h','r'};
vector<int>valueary{9,3,4,23,4,5,6};
int k=0;
root=NULL;
while(k!=7)
{
put(keyary[k],valueary[k]);
k++;
}
// preorder();
inorder();
}
BSTNode*min(BSTNode*x)
{
if(x->left==NULL)return x;
return min(x->left);
}
BSTNode*deletemin()
{
root=deletemin(root);
}
BSTNode*deletemin(BSTNode*x)
{
if(x->left==NULL)return x->right;
x->left=deletemin(x->left);
x->N=size(x->left)+size(x->right)+1;
return x;
}
BSTNode*deleteim(char k)
{
root=deleteim(root,k);
}
BSTNode*deleteim(BSTNode*x,char k)
{
if(x==NULL)return NULL;
int cmp=compare(k,x->key);
if(cmp>0)x->right=deleteim(x->right,k);
else if(cmp<0)x->left=deleteim(x->left,k);
else {
if(x->right==NULL)return x->left;
if(x->left==NULL)return x->right;
BSTNode*t=x;
x=min(t->right);
x->right=deletemin(t->right);
x->left=t->left;
}
x->N=size(x->left)+size(x->right)+1;
return x;
}
}BST;
int main()
{
BST b1;
b1.build();
// clock_t c1=clock();
b1.find('x');
// printf("%.15f",(double)((clock()-c1)/CLOCKS_PER_SEC));
b1.deleteim('s');
b1.inorder();
}