这里是题目的图片
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4d88d2765e105c70f2027cfd2a295d10.jpeg)
#include<iostream>
#include<string.h>
using namespace std;
class Node
{
public:
int value;
int ceng;
Node *left;
Node *right;
Node(int value1)
{
ceng = 1;
value = value1;
left = NULL;
right = NULL;
}
};
class BST
{
public:
int t;
int*p=new int[t];
Node* root;
BST(int t1, int* p1)
{
t = t1;
p = p1;
for (int i = 0; i < t; i++)
{
put(root,p[i]);
}
}
void put(Node* &x,int value)
{
if (x == NULL)
{
x = new Node(value);
}
else
{
if (value < x->value)
put(x->left, value);
else
put(x->right, value);
}
}
void del(Node*& x, int valuee)
{
if (root == NULL)
{
cout << "真的不好意思,没有这个结点!" << endl;
return;
}
if (x == NULL)
{
}
else
{
if (x->value == valuee)
{
if (x->left != NULL && x->right == NULL)
{
x = x->left;
}
else
{
if (x->right != NULL && x->left == NULL)
{
x = x->right;
}
if (x->right != NULL && x->left != NULL)
{
Node* y = x->right;
while (y->left != NULL)
{
y = y->left;
}
y->left = x->left;
x = x->right;
}
if (x->right == NULL && x->left == NULL)
{
x = NULL;
}
}
}
else
{
if (valuee < x->value)
del(x->left, valuee);
else
del(x->right, valuee);
}
}
}
void printtree(Node*& x)
{
if (root == NULL)
{
cout << "真的不好意思,这是一个空树" << endl;
return;
}
if (x != NULL)
{
if (x->left != NULL)
{
printtree(x->left);
}
cout << x->value << " ";
if (x->right != NULL)
{
printtree(x->right);
}
}
}
void findlen(Node*& x,int &sum,int n)
{
if (root == NULL)
{
sum = 0;
}
if (x != NULL)
{
sum += n;
if (x->left != NULL)
{
findlen(x->left, sum, n+1);
}
if (x->right != NULL)
{
findlen(x->right, sum, n+1);
}
}
}
};
int main()
{
int t;
cout << "请输入数列长度并依次输入数列各项的值" << endl;
cin >> t;
int* p = new int[t];
for (int i = 0; i < t; i++)
{
cin >> p[i];
}
BST B(t, p);
int q;
while (1)
{
cout << "请输入您想进行的操作:" << endl << "1:中序遍历打印" << endl << "2:输出平均查找长度" << endl << "3:查找x并删除" << endl;
cin >> q;
if (q == 1)
{
B.printtree(B.root);
}
else
{
if (q == 2)
{
int s = 0;
B.findlen(B.root, s, 1);
cout << s << endl;
}
else
{
cout << "请输入要查找的字符" << endl;
int w;
cin >> w;
B.del(B.root, w);
B.printtree(B.root);
}
}
cout << endl << endl;
}
}
我这里使用链表实现,如有错误,请多多指正,感谢!