实现:

 #ifndef AVL_TREE_H
#define AVL_TREE_H #include "dsexceptions.h"
#include <iostream> // For NULL
using namespace std; // AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// void printTree( ) --> Print tree in sorted order
// ******************ERRORS********************************
// Throws UnderflowException as warranted template <typename Comparable>
class AvlTree
{
public:
AvlTree( ) : root( NULL )
{ }
AvlTree( const AvlTree & rhs ) : root( NULL )
{
*this = rhs;
} ~AvlTree( )
{
makeEmpty( );
} /**
* Find the smallest item in the tree.
* Throw UnderflowException if empty.
*/
const Comparable & findMin( ) const
{
if( isEmpty( ) )
throw UnderflowException( );
return findMin( root )->element;
} /**
* Find the largest item in the tree.
* Throw UnderflowException if empty.
*/
const Comparable & findMax( ) const
{
if( isEmpty( ) )
throw UnderflowException( );
return findMax( root )->element;
} /**
* Returns true if x is found in the tree.
*/
bool contains( const Comparable & x ) const
{
return contains( x, root );
} /**
* Test if the tree is logically empty.
* Return true if empty, false otherwise.
*/
bool isEmpty( ) const
{
return root == NULL;
} /**
* Print the tree contents in sorted order.
*/
void printTree( ) const
{
if( isEmpty( ) )
cout << "Empty tree" << endl;
else
printTree( root );
} /**
* Make the tree logically empty.
*/
void makeEmpty( )
{
makeEmpty( root );
} /**
* Insert x into the tree; duplicates are ignored.
*/
void insert( const Comparable & x )
{
insert( x, root );
} /**
* Remove x from the tree. Nothing is done if x is not found.
*/
void remove( const Comparable & x )
{
cout << "Sorry, remove unimplemented; " << x <<
" still present" << endl;
} /**
* Deep copy.
*/
const AvlTree & operator=( const AvlTree & rhs )
{
if( this != &rhs )
{
makeEmpty( );
root = clone( rhs.root );
}
return *this;
} private:
struct AvlNode
{
Comparable element;
AvlNode *left;
AvlNode *right;
int height; AvlNode( const Comparable & theElement, AvlNode *lt,
AvlNode *rt, int h = )
: element( theElement ), left( lt ), right( rt ), height( h ) { }
}; AvlNode *root; /**
* Internal method to insert into a subtree.
* x is the item to insert.
* t is the node that roots the subtree.
* Set the new root of the subtree.
*/
void insert( const Comparable & x, AvlNode * & t )
{
if( t == NULL )
t = new AvlNode( x, NULL, NULL );
else if( x < t->element )
{
insert( x, t->left );
if( height( t->left ) - height( t->right ) == )
if( x < t->left->element )
rotateWithLeftChild( t );
else
doubleWithLeftChild( t );
}
else if( t->element < x )
{
insert( x, t->right );
if( height( t->right ) - height( t->left ) == )
if( t->right->element < x )
rotateWithRightChild( t );
else
doubleWithRightChild( t );
}
else
; // Duplicate; do nothing
t->height = max( height( t->left ), height( t->right ) ) + ;
} /**
* Internal method to find the smallest item in a subtree t.
* Return node containing the smallest item.
*/
AvlNode * findMin( AvlNode *t ) const
{
if( t == NULL )
return NULL;
if( t->left == NULL )
return t;
return findMin( t->left );
} /**
* Internal method to find the largest item in a subtree t.
* Return node containing the largest item.
*/
AvlNode * findMax( AvlNode *t ) const
{
if( t != NULL )
while( t->right != NULL )
t = t->right;
return t;
} /**
* Internal method to test if an item is in a subtree.
* x is item to search for.
* t is the node that roots the tree.
*/
bool contains( const Comparable & x, AvlNode *t ) const
{
if( t == NULL )
return false;
else if( x < t->element )
return contains( x, t->left );
else if( t->element < x )
return contains( x, t->right );
else
return true; // Match
}
/****** NONRECURSIVE VERSION*************************
bool contains( const Comparable & x, AvlNode *t ) const
{
while( t != NULL )
if( x < t->element )
t = t->left;
else if( t->element < x )
t = t->right;
else
return true; // Match return false; // No match
}
*****************************************************/ /**
* Internal method to make subtree empty.
*/
void makeEmpty( AvlNode * & t )
{
if( t != NULL )
{
makeEmpty( t->left );
makeEmpty( t->right );
delete t;
}
t = NULL;
} /**
* Internal method to print a subtree rooted at t in sorted order.
*/
void printTree( AvlNode *t ) const
{
if( t != NULL )
{
printTree( t->left );
cout << t->element << endl;
printTree( t->right );
}
} /**
* Internal method to clone subtree.
*/
AvlNode * clone( AvlNode *t ) const
{
if( t == NULL )
return NULL;
else
return new AvlNode( t->element, clone( t->left ), clone( t->right ), t->height );
}
// Avl manipulations
/**
* Return the height of node t or -1 if NULL.
*/
int height( AvlNode *t ) const
{
return t == NULL ? - : t->height;
} int max( int lhs, int rhs ) const
{
return lhs > rhs ? lhs : rhs;
} /**
* Rotate binary tree node with left child.
* For AVL trees, this is a single rotation for case 1.
* Update heights, then set new root.
*/
void rotateWithLeftChild( AvlNode * & k2 )
{
AvlNode *k1 = k2->left;
k2->left = k1->right;
k1->right = k2;
k2->height = max( height( k2->left ), height( k2->right ) ) + ;
k1->height = max( height( k1->left ), k2->height ) + ;
k2 = k1;
} /**
* Rotate binary tree node with right child.
* For AVL trees, this is a single rotation for case 4.
* Update heights, then set new root.
*/
void rotateWithRightChild( AvlNode * & k1 )
{
AvlNode *k2 = k1->right;
k1->right = k2->left;
k2->left = k1;
k1->height = max( height( k1->left ), height( k1->right ) ) + ;
k2->height = max( height( k2->right ), k1->height ) + ;
k1 = k2;
} /**
* Double rotate binary tree node: first left child.
* with its right child; then node k3 with new left child.
* For AVL trees, this is a double rotation for case 2.
* Update heights, then set new root.
*/
void doubleWithLeftChild( AvlNode * & k3 )
{
rotateWithRightChild( k3->left );
rotateWithLeftChild( k3 );
} /**
* Double rotate binary tree node: first right child.
* with its left child; then node k1 with new right child.
* For AVL trees, this is a double rotation for case 3.
* Update heights, then set new root.
*/
void doubleWithRightChild( AvlNode * & k1 )
{
rotateWithLeftChild( k1->right );
rotateWithRightChild( k1 );
}
}; #endif

测试:

 #include <iostream>
#include "AvlTree.h"
using namespace std; // Test program
int main( )
{
AvlTree<int> t, t2;
int NUMS = ;
const int GAP = ;
int i; cout << "Checking... (no more output means success)" << endl; for( i = GAP; i != ; i = ( i + GAP ) % NUMS )
t.insert( i ); if( NUMS < )
t.printTree( );
if( t.findMin( ) != || t.findMax( ) != NUMS - )
cout << "FindMin or FindMax error!" << endl; t2 = t; for( i = ; i < NUMS; i++ )
if( !t2.contains( i ) )
cout << "Find error1!" << endl;
if( t2.contains( ) )
cout << "ITEM_NOT_FOUND failed!" << endl; cout << "Test finished" << endl;
return ;
}

数据结构-AVL树的更多相关文章

  1. 数据结构-AVL树的旋转

    http://blog.csdn.net/GabrieL1026/article/details/6311339 平衡二叉树在进行插入操作的时候可能出现不平衡的情况,AVL树即是一种自平衡的二叉树,它 ...

  2. 简单数据结构———AVL树

    C - 万恶的二叉树 Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:32768KB     64b ...

  3. JAVA数据结构--AVL树的实现

    AVL树的定义 在计算机科学中,AVL树是最先发明的自平衡二叉查找树.在AVL树中任何节点的两个子树的高度最大差别为1,所以它也被称为高度平衡树.查找.插入和删除在平均和最坏情况下的时间复杂度都是.增 ...

  4. 数据结构--Avl树的创建,插入的递归版本和非递归版本,删除等操作

    AVL树本质上还是一棵二叉搜索树,它的特点是: 1.本身首先是一棵二叉搜索树.   2.带有平衡条件:每个结点的左右子树的高度之差的绝对值最多为1(空树的高度为-1).   也就是说,AVL树,本质上 ...

  5. 再回首数据结构—AVL树(一)

    前面所讲的二叉搜索树有个比较严重致命的问题就是极端情况下当数据以排序好的顺序创建搜索树此时二叉搜索树将退化为链表结构因此性能也大幅度下降,因此为了解决此问题我们下面要介绍的与二叉搜索树非常类似的结构就 ...

  6. 再回首数据结构—AVL树(二)

    前面主要介绍了AVL的基本概念与结构,下面开始详细介绍AVL的实现细节: AVL树实现的关键点 AVL树与二叉搜索树结构类似,但又有些细微的区别,从上面AVL树的介绍我们知道它需要维护其左右节点平衡, ...

  7. 第三十二篇 玩转数据结构——AVL树(AVL Tree)

          1.. 平衡二叉树 平衡二叉树要求,对于任意一个节点,左子树和右子树的高度差不能超过1. 平衡二叉树的高度和节点数量之间的关系也是O(logn) 为二叉树标注节点高度并计算平衡因子 AVL ...

  8. Java数据结构——AVL树

    AVL树(平衡二叉树)定义 AVL树本质上是一颗二叉查找树,但是它又具有以下特点:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树,并且拥有自平衡机制.在AV ...

  9. 数据结构 - AVL 树

    简介 基本概念 AVL 树是最早被发明的自平衡的二叉查找树,在 AVL 树中,任意结点的两个子树的高度最大差别为 1,所以它也被称为高度平衡树,其本质仍然是一颗二叉查找树. 结合二叉查找树,AVL 树 ...

随机推荐

  1. Linux的中断 & 中断和异常的区别

    参考 http://www.yesky.com/20010813/192117.shtml 结构化程序设计思想认为:程序 = 数据结构 + 算法.数据结构体现了整个系统的构架,所以数据结构通常都是代码 ...

  2. jQuery动态加载脚本 $.getScript();

    jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) {       /*          ...

  3. MFC编程入门之前言

    本系列主要偏重于理论方面的知识,目的是打好底子,练好内功,在使用VC++编程时不至于丈二和尚摸不着头脑.本系列也会涉及到VC++的原理性的东西,同样更重视实用性,学完本系列以后,基本的界面程序都能很容 ...

  4. 闹钟--alarmManager

    1.AlarmManager,顾名思义,就是“提醒”,是Android中 常用的一种系统级别的提示服务,在特定的时刻为我们广播一个指定的Intent.简单的说就是我们设定一个时间,然后在该时间到来 时 ...

  5. (转)springAOP解析-2

    原文地址:http://hzbook.group.iteye.com/group/wiki/2262-Spring 3.3.4  AOP拦截器链的调用在了解了对目标对象的直接调用以后,我们开始进入AO ...

  6. iOS 使用drawRect: 绘制虚线椭圆

    iOS 使用drawRect: 绘制虚线椭圆 1:首先如果要使用 drawRect 绘图 要导入 CoreGraphics.framework 框架 然后 创建 自定义view, 即是 myView继 ...

  7. 例题:for循环迭代法。一个棋盘有n个格子,第一个格子有一粒米,第二个格子有两粒米,第三个格子有四粒米,依次类推,第n个格子里有多少粒米,棋盘里一共有多少粒米。

    decimal a = 1;//定义初始值,decimal可以定义比较长的数值            decimal sum = 1;            Console.WriteLine(&qu ...

  8. Android屏幕适配原理

    几个概念: 1) 屏幕密度(dpi) :dot per inch,即每英寸像素数. ldpi(120),mdpi(160),hdpi(240),xhdpi(320) 计算方法: 以480x854,4. ...

  9. android 内存泄露之jni local reference table overflow (max=512)

    在android项目中要实现一个需求 为了性能的要求只能用c代码来实现功能. 这样就牺牲了java跨平台性. 通过加载.so的方式,把用c实现的模块集成到app中. android提供jni层,作为一 ...

  10. noip2016酱油记day1

    真的是noip2016酱油记了. t1模拟,应该可以过. t2用了个简单的桶瞎搞,估计剩50pt了. t3直接不会写. 心好累... 考的分数肯定没去年高. 但不论如何,明天正常发挥就好. 正常发挥下 ...