數據結構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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章