二叉排序樹 插入 遍歷 查找 (V0.2)

初稿,後面再完善

執行成功

#include <stdio.h>
#include <stdlib.h>
 
typedef struct BiTNode{ 
 char data;   
 struct BiTNode *lchild,*rchild;  
 }BiTNode,*BiTree;   


//插入
 void insert(BiTree *t, int key)
 {
	 if(*t == NULL)
	 {
		 (*t) = (BiTree)malloc(sizeof(BiTNode));
		 (*t)->data = key;
		 (*t)->lchild = (*t)->rchild = NULL;
	 }
	 else{
		 if(key == (*t)->data)
		 {
			 printf("該數已存在\n");
			 return ;
		 }
		 else if(key < (*t)->data)
			 insert(&((*t)->lchild), key);	 
		 else if(key > (*t)->data)
			insert(&((*t)->rchild), key); 			 
	 }
 
}
//查找
 BiTree search(BiTree t, int key)
 {
	 if(t)
	 {
		 if(key == t->data)
			 return t;
		 else if(key < t->data)
			 return search(t->lchild, key);
		 else if(key > t->data)
			 return search(t->rchild, key);
	 }
	 return NULL;
 } 


  void print(BiTree t) //中序排序  按大小
 {
	 if(t)
	 {	 
		 print(t->lchild);
		 printf("%d ", t->data);
		 print(t->rchild);
	}
 }
//刪除
void delete(BiTree *t)
{
	BiTree pre, s;
	if((*t)->lchild == NULL) //左子樹爲空
	{
		pre = *t;
		*t = (*t)->rchild;
		free(pre);
		pre = NULL;
	}
	else if((*t)->rchild == NULL) //左子樹爲空
	{
		pre = *t;
		*t = (*t)->lchild;
		free(pre);
		pre = NULL;
	}
	else{
		pre = (*t)->lchild;
		s = (*t)->lchild;
		while(s->rchild)
		{
			pre = s;
			s = s->rchild;
		}
		(*t)->data = s->data;
		if(pre != s)
			pre->rchild = s->lchild;
		else
			(*t)->lchild = s->lchild;
		free(s);
		pre = NULL;	
	}
}

int delete_bst(BiTree *t, int key)
{
	if(!(*t))
	{
		printf("未找到\n");
		return 0;
	}
	else{
		if(key == (*t)->data)
			delete(t);
		else if(key < (*t)->data)
			delete_bst(&((*t)->lchild), key);
		else if(key > (*t)->data)
			delete_bst(&((*t)->rchild), key);
	}	
}



 int main()
 {
	 BiTree t=NULL, p=NULL;
	 int key, mode;
	 while(1)
	 {
		printf("1 插入, 2 查找, 3 中序遍歷, 4刪除\n");
		scanf("%d", &mode);
		switch(mode)
		{
			case 1:
				printf("請輸入要插入數:");
				scanf("%d", &key);
				insert(&t, key);
				break;
			case 2:
				if(t == NULL)
					printf("樹爲空\n");
				else	
				{
					printf("請輸入查找的數:");
					scanf("%d", &key);
					p = search(t, key);
					if(p)
						printf("查找成功\n");
					else
						printf("查找失敗\n");
				}
				break;
			case 3:
				if(t == NULL)
					printf("樹爲空\n");
				else
				{
					printf("中序遍歷:");
					print(t);
					printf("\n");
				}
				break;
			case 4:
				printf("請輸入刪除的數:");
				scanf("%d", &key);
				delete_bst(&t, key);
				break;
		}		
	 } 
	 return 0;
 }





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