二叉搜索树ADT

	#include<stdio.h>
	#include<stdlib.h>

	typedef int ElementType;
	typedef struct BST {
		ElementType data;
		struct BST *left;
		struct BST *right;
	}*BST;

	BST BST_Insert(BST *T, ElementType x);
	BST BST_Create(ElementType s[], int length);
	BST BST_FindMin(BST T);
	BST BST_Delete(ElementType x, BST T);

	BST BST_Insert(BST *T, ElementType x) {
	
		if (!*T) {
			*T = (BST)malloc(sizeof(struct BST));
			(*T)->data = x;
			(*T)->left = (*T)->right = NULL;
		}
		else {
			if ((*T)->data > x)
				(*T)->left = BST_Insert(&(*T)->left, x);
			else if ((*T)->data < x)
				(*T)->right = BST_Insert(&(*T)->right, x);
		}

		return *T;
	}

	BST BST_Create(ElementType s[], int length) {

		BST T = NULL;
		for (int i = 0; i < length; i++)
			T = BST_Insert(&T, s[i]);

		return T;
	}

	BST BST_FindMin(BST T) {

		if (!T) return NULL;

		if (!T->left) return T;
		else return BST_FindMin(T->left);

	}

	BST BST_Delete(ElementType x, BST T) {

		if (!T)
			return NULL;
		else if (x < T->data)
			T->left = BST_Delete(x, T->left);
		else if (x > T->data)
			T->right = BST_Delete(x, T->right);
		else {
			if (T->left && T->right) {
				BST tmp = BST_FindMin(T->right);
				T->data = tmp->data;
				T->right = BST_Delete(tmp->data, T->right);
			}
			else
			{
				BST tmp = T;
				if (!T->left)
					T = T->right;
				else if (!T->right)
					T = T->left;
				free(tmp);
			}
		}

		return T;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值