zoukankan      html  css  js  c++  java
  • AVL树的调整(笔记)

    1.定义

    • 二叉树:二叉树是每个结点最多有两个子树的树结构。
    • 二叉搜索树:二叉搜索树(Binary Search Tree),它或者是一棵空树,或者是具有下列性质的二叉树:
    1.  若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
    2. 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
    3. 它的左、右子树也分别为二叉搜索树。
    • 平衡二叉搜索树:平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树,且具有以下性质:
    1. 它是一 棵空树
    2. 或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

    2.平衡二叉搜索树的基本操作:

    • 插入元素:需要调整(左单旋,右单旋,左右单旋,右左单旋)以维持树的平衡
    • 查找元素
    • 删除元素

    3.错误报告:

    • 在进行左单旋时,应该先将B的右子树分给A的左子树,否则会造成A的左子树是A的死循环(右单旋同理)
    • 在进行插入操作后,一点要更新树的高度
    • 对于指针为NULL一定要细心处理,切勿遗忘

    4.代码示例:

    #include<iostream>
    #include<cstdio>
    #include<stack>
    using namespace std;
    typedef struct AVLNode *position;
    typedef position AVLTree;
    struct AVLNode{
    	int data;
    	AVLTree left;
    	AVLTree right;
    	int h;
    };
    int GetHight(AVLTree A){
    	if(A == NULL)	return -1;
    	return A->h;
    }
    //左单旋
    AVLTree SLR(AVLTree A){
    	AVLTree B = A->left;
    	A->left = B->right;
    	B->right = A;
    	A->h = max(GetHight(A->left),GetHight(A->right))+1;
    	B->h = max(GetHight(B->left),GetHight(B->right))+1;
    	return B;
    } 
    //右单旋
    AVLTree SRR(AVLTree A){
    	AVLTree B = A->right;
    	A-> right = B->left;
    	B->left = A;
    	A->h = max(GetHight(A->left),GetHight(A->right))+1;
    	B->h = max(GetHight(B->left),GetHight(B->right))+1;
    	return B;
    }
    //左右双旋
    AVLTree DLRR(AVLTree A){
    	AVLTree B = A->left;
    	A->left = SRR(B);
    	return SLR(A);
    }
    //右左双旋 
    AVLTree DRLR(AVLTree A){
    	AVLTree B = A->right;
    	A->right = SLR(B);
    	return SRR(A);
    }
    AVLTree Insert(AVLTree T,int x){
    	if(T == NULL){
    		T = new AVLNode();
    		T->data = x;
    		T->left = NULL;
    		T->right = NULL;
    		T->h = 0;
    	}else if(x < T->data){
    		T->left = Insert(T->left,x);
    		if(GetHight(T->left) - GetHight(T->right) == 2)
    			if(x < T->left->data)	T = SLR(T);
    			else T = DLRR(T);
    	}else if(x > T->data){
    		T->right = Insert(T->right,x);
    		if(GetHight(T->left)-GetHight(T->right) == -2)
    			if(x > T->right->data)	T = SRR(T);
    			else	T = DRLR(T);
    	}
    	T->h = max(GetHight(T->left),GetHight(T->right))+1;
    	return T;
    }
  • 相关阅读:
    Entity SQL 初入
    ObjectQuery查询及方法
    Entity Framework 的事务 DbTransaction
    Construct Binary Tree from Preorder and Inorder Traversal
    Reverse Linked List
    Best Time to Buy and Sell Stock
    Remove Duplicates from Sorted Array II
    Reverse Integer
    Implement Stack using Queues
    C++中const限定符的应用
  • 原文地址:https://www.cnblogs.com/long98/p/10352179.html
Copyright © 2011-2022 走看看