1. 题目
示例输入
12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1
10 17
6
12
示例输出
12 13 16
4 6 8 10 12 13 16 18
4 8 10 13 16 18
2. 代码
#include <iostream>
using namespace std;
typedef struct tree{
int data;
struct tree *lc, *rc;
}Tree;
Tree* CreateTree(){
int tmp;
cin >> tmp;
if(tmp == -1) return NULL;
Tree *t = (Tree*)malloc(sizeof(Tree));
t->data = tmp;
t->lc = CreateTree();
t->rc = CreateTree();
return t;
}
void Search(Tree *t, int a, int b){
if(t){
if(t->data >= b){
Search(t->lc, a, b);
}
else if(t->data <= a){
Search(t->lc, a, b);
}
else{
Search(t->lc, a, b);
cout << t->data << " ";
Search(t->rc, a, b);
}
}
}
Tree* Insert(Tree *t, int x){
if(!t){
t = (Tree*)malloc(sizeof(Tree));
t->data = x;
t->lc = NULL;
t->rc = NULL;
return t;
}
if(t->data == x) return t;
if(t->data > x){
t->lc = Insert(t->lc, x);
return t;
}
if(t->data < x){
t->rc = Insert(t->rc, x);
return t;
}
}
void InOrdOutput(Tree *t){
if(t){
InOrdOutput(t->lc);
cout << t->data << " ";
InOrdOutput(t->rc);
}
}
void Remove(Tree* &t){
if(!t->lc && !t->rc){
t = NULL;
}
else if(!t->lc){
t = t->rc;
}
else if(!t->rc){
t = t->lc;
}
else{
Tree *p = t->lc;
while(p->rc){
p = p->rc;
}
p->rc = t->rc;
t = t->lc;
}
}
void Delete(Tree* &t, int x){
if(t->data == x){
Remove(t);
}
else if(t->data > x){
Delete(t->lc, x);
}
else{
Delete(t->rc, x);
}
}
int main(){
Tree *t = CreateTree();
int a, b, x, y;
cin >> a >> b >> x >> y;
Search(t, a, b);
cout << endl;
t = Insert(t, x);
InOrdOutput(t);
cout << endl;
Delete(t, x);
Delete(t, y);
InOrdOutput(t);
cout << endl;
return 0;
}