Description
假设二叉排序树以后继线索链表作存储结构,编写程序,满足以下要求:
输出该二叉排序树中所有大于a小于b的关键字;
在二叉排序树中插入一个关键字;
在二叉排序树中删除一个关键字。
Input
第一行按先序输入二叉排序树各结点(结点值大于0),其中-1表示取消建立子树结点;第二行输入要求1中a、b,用空格隔开;第三行输入要求2中要插入的关键字;第四行输入要求3中要删除的关键字。
Output
按照中序序列,分三行输出要求1、要求2和要求3的结果。
-
Sample Input
12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1 10 17 6 12
-
Sample Output
12 13 16 4 6 8 10 12 13 16 18 4 8 10 13 16 18
#include<stdio.h>
#include<stdlib.h>
typedef struct BinaryTree{
int num;
struct BinaryTree *lchild;
struct BinaryTree *rchild;
}BinaryTree,*Bintree;
void CreatBTree(Bintree *List){
int n;
scanf("%d", &n);
if(n == -1) *List = NULL;
else{
*List = (Bintree)malloc(sizeof(BinaryTree));
(*List)->num = n;
CreatBTree(&((*List)->lchild));
CreatBTree(&((*List)->rchild));
}
}
void search(Bintree List, int x, int y){
if(List){
search(List->lchild, x, y);
if((List->num > x) && (List->num < y)){
printf("%d ", List->num);
}
search(List->rchild, x, y);
}
}
void insert(Bintree *List, int a){
if(!*List){
*List = (Bintree)malloc(sizeof(BinaryTree));
(*List)->num = a;
(*List)->lchild = (*List)->rchild = NULL;
return;
}
if((*List)->num == a){
return;
}
if((*List)->num > a){
insert(&((*List)->lchild), a);
}
else{
insert(&((*List)->rchild), a);
}
}
void output(BinaryTree *List){
if(List){
output(List->lchild);
printf("%d ", List->num);
output(List->rchild);
}
}
void kill(Bintree *List){
Bintree T;
if(!(*List)->lchild && !(*List)->rchild){
*List = NULL;
}
else if(!(*List)->lchild){
*List = (*List)->rchild;
}
else if(!(*List)->rchild){
*List = (*List)->lchild;
}
else{
T = (*List)->lchild;
while(T->rchild){
T = T->rchild;
}
T->rchild = (*List)->rchild;
*List = (*List)->lchild;
}
}
bool Delete(Bintree *List, int m){
if(!(*List)){
return false;
}
else if((*List)->num == m){
kill(List);
return true;
}
else if((*List)->num > m){
Delete(&((*List)->lchild), m);
}
else{
Delete(&((*List)->rchild), m);
}
}
int main(){
int x, y, a, b;
Bintree List = NULL;
CreatBTree(&List);
scanf("%d%d%d%d", &x, &y, &a, &b);
search(List, x, y);
printf("\n");
insert(&List, a);
output(List);
printf("\n");
Delete(&List, a);
Delete(&List, b);
output(List);
printf("\n");
return 0;
}