平衡(AVL)二叉树

  • AVL树 解决二叉查找(BST)树所有节点都倾向一边,退化成链表的缺点
  • 具有二叉查找树的全部特性。
  • 每个节点的左子树和右子树的高度差至多等于1

定义节点

#include
#include
#include
using namespace std;

typedef int KeyType;
typedef struct AVLNode
{
     
	AVLNode* leftchild;
	AVLNode* parent;
	AVLNode* rightchild;
	int balance; // -1 ,0 ,1 平衡因子
	KeyType key;
}AVLNode, * AVLTree;

新建、释放节点

AVLNode* Buynode(KeyType kx)
{
     
	AVLNode* s = (AVLNode*)malloc(sizeof(AVLNode));
	if (nullptr == s) exit(1);
	memset(s, 0, sizeof(AVLNode));
	s->key = kx;
	return s;
}
void Freenode(AVLNode* p)
{
     
	free(p);
}

左旋

void RotateLeft(AVLTree& root, AVLNode* ptr)
{
     
	AVLNode* newroot = ptr->rightchild;
	newroot->parent = ptr->parent;// 1
	ptr->rightchild = newroot->leftchild;
	if (newroot->leftchild != nullptr)
	{
     
		newroot->leftchild->parent = ptr;// 2
	}
	newroot->leftchild = ptr;
	if (ptr->parent == nullptr)
	{
     
		root = newroot;
	}
	else
	{
     
		if (ptr->parent->leftchild == ptr)
		{
     
			ptr->parent->leftchild = newroot;
		}
		else
		{
     
			ptr->parent->rightchild = newroot;
		}
	}
	ptr->parent = newroot;	 // 3
}

右旋

void RotateRight(AVLTree& root, AVLNode* ptr)
{
     
	AVLNode* newroot = ptr->leftchild;
	newroot->parent = ptr->parent;//1
	ptr->leftchild = newroot->rightchild;
	if (newroot->rightchild != nullptr)
	{
     
		newroot->rightchild->parent = ptr;
	}
	newroot->rightchild = ptr;
	if (ptr->parent == nullptr)
	{
     
		root = newroot;
	}
	else
	{
     
		if (ptr->parent->leftchild == ptr)
		{
     
			ptr->parent->leftchild = newroot;
		}
		else
		{
     
			ptr->parent->rightchild = newroot;
		}
	}
	ptr->parent = newroot;
}

更多详情请访问此处

图论

你可能感兴趣的:(算法,二叉树)