zoukankan      html  css  js  c++  java
  • AVL树实现

    AVL树的节点声明

    #ifndef _AvlTree_H
    
    struct AvlNode;
    typedef struct AvlNode *Position;
    typedef struct AvlNode *AvlTree;
    
    AvlTree MakeEmpty(AvlTree T);
    Position Find( ElementType X,AvlTree T);
    Position FindMin(AvlTree T);
    Position FindMax(AvlTree T);
    AvlTree Insert(ElementType X,AvlTree T);
    AvlTree Delete(ElementType X,AvlTree T);
    ElementType Retrieve(Position P);
    
    #endif
    
    struct AvlNode
    {
    	ElementType Element;
    	AvlTree Left;
    	AvlTree Right;
    	int Height;
    };
    

    计算AVL节点高度

    static int Height(Position P)
    {
    	if(P == NULL)
    		return -1;
    	else
    		return P->Height;
    }
    

    向AVL树插入节点

    AvlTree Insert(ElementType X,AvlTree T)
    {
    	if(T == NULL)
    	{
    		T = malloc(sizeof(struct AvlNode));
    		if(T == NULL)
    			FataError("Out of space!!!");
    		else
    		{
    			T->Element = X;T->Height = 0;
    			T->Left = T->Right = NULL;
    		}
    	}
    	else if(X < T->Element)
    	{
    		T->Left = Insert(X,T->Left);
    		if(Height(T->Left)-Height(T->Right) == 2)
    			if(X < T->Left->Element)
    				T = SingleRotateWinthLeft(T);
    			else
    				T = DoubleRotateWithLeft(T);
    	}
    	else if (X > T->Element)
    	{
    		T->Right = Insert(X,T->Right);
    		if(Height(T->Right) - Height(T->Left) == 2)
    			if(X > T->Right->Element)
    				T = SingleRotateWinthRight(T);
    			else
    				T = DoubleRotateWithRight(T);
    	}
    	T->Height = Max(Height(T->Left),Height(T->Right)) + 1;
    	return T;
    }
    

    执行单旋转操作

    static Position SingleRotateWinthLeft(Position K2)
    {
    	Position K1;
    	K1 = k2->Left;
    	K2->Left = K1->Right;
    	k1->Right = K2;
    	K2->Height = Max(Height(K2->Left),Height(K2->Right)) + 1;
    	K1->Height = Max(Height(K1->Left),K2->Height)) + 1;
    	return K1;
    }
    

    执行双旋转操作

    static Position DoubleRotateWithLeft(Position K3)
    {
    	K3->Left = SingleRotateWithRight(K3->Left);
    	return SingleRotateWithLeft(K3);
    }
  • 相关阅读:
    intel instruction 指令速查
    WinDbg双机调试配置
    MSDN上关于WinDbg的手册
    build temu error about SDL
    taintCheck的实现
    Vim使用taglist功能
    Windows编写driver
    cabal替代脚本
    怎样理解Functor与Monad
    haskell基本语法
  • 原文地址:https://www.cnblogs.com/y3w3l/p/6363666.html
Copyright © 2011-2022 走看看