AVL树C语言完整实现

AVL树的介绍见http://blog.csdn.net/pngynghay/article/details/22443525,本文给出的是AVL树的一种实现。

采用非递归方式,效率较好,经过常规测试。

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>

typedef enum
{
	EH = 0,
	LH = 1,
	RH = -1
}bh_t;


typedef enum
{
	FALSE = 0,
	TRUE = 1
}bool_t;

typedef int ElemType;

typedef struct BSTNode
{
	ElemType key;
	int bf;
	struct BSTNode *lchild,*rchild,*parent;
}BSTNode,*BSTree;

bool_t  searchAVL(BSTree root,ElemType key, BSTNode **parent)
{
	BSTNode *tmp = NULL;
	assert(root != NULL);
	*parent = root->parent;
	tmp = root;
	while(NULL != tmp)
	{
		if(tmp->key == key)
		{
			return TRUE;
		}

		*parent = tmp;
		if(tmp->key > key)
		{
			tmp = tmp->lchild;
		}
		else
		{
			tmp = tmp->rchild;
		}
	}
	return FALSE;
}

/* get the minimum node*/
BSTNode* minNode(BSTNode* root)
{
	if (root == NULL)
	{
		return NULL;
	}
	while (root->lchild != NULL)
	{
		root = root->lchild;
	}
	return root;
}

/* get the maximum node*/
BSTNode* maxNode(BSTNode* root)
{
	if (root == NULL)
	{
		return NULL;
	}
	while (root->rchild != NULL)
	{
		root = root->rchild;
	}
	return root;
}

/* get the previous node*/
BSTNode* preNode(BSTNode* target)
{
	if (target == NULL)
	{
		return NULL;
	}
	if (target->lchild != NULL)
	{
		return maxNode(target->lchild);
	}
	while ((target->parent!=NULL) && (target!=target->parent->rchild))
	{
		target = target->parent;
	}
	return target->parent;
}

/* get the next node*/
BSTNode* nextNode(BSTNode* target)
{
	if (target == NULL)
	{
		return NULL;
	}
	if (target->rchild != NULL)
	{
		return minNode(target->rchild);
	}
	while ((target->parent!=NULL) && (target!=target->parent->lchild))
	{
		target = target->parent;
	}
	return target->parent;
}

BSTNode* leftbalance(BSTNode* root, BSTNode* parent, BSTNode* child)
{
	BSTNode *cur;
	assert((parent != NULL)&&(child != NULL));
	/* LR */
	if (child->bf == RH)
	{
		cur = child->rchild;
		cur->parent = parent->p
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值