数据结构25——二叉排序树的插入和删除(严9.35、9.36和9.37)【*,&不懂】

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值