二叉搜索树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;
	}

猜你喜欢

转载自blog.csdn.net/hang981601026/article/details/81808226