输入若干个不同的正整数(以0结束),按顺序建立一颗二叉排序树,输出中序遍历结果。再输入一个数X,在建好的二叉排序树中查找有无关键字X这个结点,有则删除该节点,无则插入这个结点,删除或插入后还要保证满足二叉排序树的要求。最后请用邻接表的形式再次输入该二叉排序树。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
struct node {
node* left;
node*right;
int val;
};
node*root;
void build(int k, struct node*&x)
{
if (x == NULL)
{
x = new struct node;
x->left = NULL;
x->right = NULL;
x->val = k;
}
else
{
if (k < x->val)
{
build(k, x->left);
}
else
{
build(k, x->right);
}
}
}
void puts(struct node *x)
{
if (x != NULL)
{
puts(x->left);
cout << x->val ;
puts(x->right);
}
}
void exers(node *&x)
{
if (x->left == NULL && x->right == NULL)
{
node *n = root;
if (n->val == x->val)
root = NULL;
while (1)
{
if (n->left!=NULL&&n->left->val == x->val)
{
n->left = NULL;
break;
}
if (n->right!=NULL&&n->right->val == x->val)
{
n->right = NULL;
break;
}
if (x->val > n->val)
{
n = n->right;
}
else
{
n = n->left;
}
}
}
else
{
if (x->left != NULL && x->right != NULL)
{
node*n = x->left;
while (1)
{
if (n->right == NULL)
{
n->right = x->right;
break;
}
n = n->right;
}
x->right = x->left->right;
x->val = x->left->val;
x->left = x->left->left;
}
else
{
if (x->left != NULL)
{
x->right = x->left->right;
x->val = x->left->val;
x->left = x->left->left;
}
else
{
x->left = x->right->left;
x->val = x->right->val;
x->right = x->right->right;
}
}
}
}
void finds(int x)
{
node*n = root;
while (1)
{
if (n->val == x)
{
cout << "YES" << endl;
exers(n);
return;
}
if (x > n->val)
n = n->right;
else
n = n->left;
}
}
void print(node *x)
{
if (x == NULL)
return;
cout << x->val;
if (x->left || x->right)cout << "(";
if (x->left)print(x->left);
if (x->right)cout << ",";
if (x->right)print(x->right);
if (x->left || x->right)cout << ")";
}
int main()
{
int k;
int X;
while (1)
{
cin >> k;
if (k == 0)
break;
build(k, root);
}
puts(root);
cout << endl;
cin >> X;
finds(X);
puts(root);
cout << endl;
print(root);
return 0;
}