数据结构与算法分析:树的基本操作与AVL树旋转的实现

代码源自《数据结构与算法分析——c语言描述》

二叉查找树的基本操作:

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

typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;

struct TreeNode
{
	int data;
	SearchTree Left;
	SearchTree Right;
};

SearchTree MakeEmpty(SearchTree T)
{
	if (T != NULL)
	{
		MakeEmpty(T->Left);
		MakeEmpty(T->Right);
		free(T);
	}
	return NULL;
}

Position Find(int x, SearchTree T)
{
	if (T == NULL)
		return NULL;
	else if (x < T->data)
		return Find(x, T->Left);
	else if (x > T->data)
		return Find(x, T->Right);
	else
		return T;
}

Position FindMin(SearchTree T)
{
	if (T == NULL)
		return NULL;
	else
		if (T->Left == NULL)
			return T;
		else
			FindMin(T->Left);
}

Position FindMax(SearchTree T)
{
	if (T == NULL)
		return NULL;
	else
		if (T->Right == NULL)
			return T;
		else
			FindMax;
}

SearchTree Insert(int x, SearchTree T)
{
	if (T == NULL)
	{
		//创造并返回一个单节点的树
		T = (SearchTree)malloc(sizeof(struct TreeNode));
		if (T == NULL)
		{
			printf("out of space!");
			exit(1);
		}
		else
		{
			T->data = x;
			T->Left = T->Right = NULL;
		}
	}
	else
		if (x < T->data)
			T->Left=Insert(x, T->Left);
		else
			if (x > T->data)
				T->Right=Insert(x, T->Right);

	return T;
}
SearchTree Delete(int x, SearchTree T)
{
	Position Tmpcell;
	if (T == NULL)
	{
		printf("element not found!\n");
		system("pause");
		exit(1);
	}
	else
		if (x < T->data)
			T->Left = Delete(x, T->Left);
		else
			if (x > T->data)
				T->Right = Delete(x, T->Left);
			else
				if (T->Left&&T->Right)//有两个子树(双分支)
				{
					//将右子树中最小的元素替换当前节点
					//实际上没有删除当前节点,而是改变其值为右子树中最小的值,并将该最小值节点删除
					Tmpcell = FindMin(T->Right);
					T->data = Tmpcell->data;
					T->Right = Delete(T->data, T->Right);
				}
				else//一个或无子树
				{
					Tmpcell = T;
					if (T->Left == NULL)
						T = T->Right;
					else if(T->Right == NULL)
						T = T->Left;
					free(Tmpcell);
				}
	return T;
}

void PrintElement(Position p)
{
	printf("%d\t", p->data);
}

void PrintTree(SearchTree T)
{
	if (T != NULL)
	{
		PrintTree(T->Left);
		PrintElement(T);
		PrintTree(T->Right);
	}
}

功能测试:

int main()
{
	SearchTree tree;
	tree = NULL;
	int temp;
	char c;
	do
	{
		printf("enter :\n");
		scanf("%c", &c);
		switch (c)
		{
		case ('i'):
			printf("please enter a num you want to insert:");
			scanf("%d", &temp);
			tree=Insert(temp, tree);
			while ((c = getchar()) != '\n')
				scanf("%c", &c);
			break;
		case ('d'):
			printf("please enter a num you want to delete:");
			scanf("%d", &temp);
			tree=Delete(temp, tree);
			while ((c = getchar()) != '\n')
				scanf("%c", &c);
			break;
		case('s'):
			printf("we are goning to show you the data after sorted:\n");
			PrintTree(tree);
			while ((c = getchar()) != '\n')
				scanf("%c", &c);
		};
	} while (c != 'e');

	system("pause");
	return 0;
}

avl树的旋转:

    原文作者:AVL树
    原文地址: https://blog.csdn.net/weixin_40505645/article/details/80515673
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞