AVLTREES文档格式.docx

上传人:b****6 文档编号:16975646 上传时间:2022-11-27 格式:DOCX 页数:21 大小:222.16KB
下载 相关 举报
AVLTREES文档格式.docx_第1页
第1页 / 共21页
AVLTREES文档格式.docx_第2页
第2页 / 共21页
AVLTREES文档格式.docx_第3页
第3页 / 共21页
AVLTREES文档格式.docx_第4页
第4页 / 共21页
AVLTREES文档格式.docx_第5页
第5页 / 共21页
点击查看更多>>
下载资源
资源描述

AVLTREES文档格式.docx

《AVLTREES文档格式.docx》由会员分享,可在线阅读,更多相关《AVLTREES文档格式.docx(21页珍藏版)》请在冰豆网上搜索。

AVLTREES文档格式.docx

balanceFactor=height(right-subtree)-height(left-subtree)

IfbalanceFactorisnegative,thenodeis"

heavyontheleft"

sincetheheightoftheleftsubtreeisgreaterthantheheightoftherightsubtree.WithbalanceFactorpositive,thenodeis"

heavyontheright."

AbalancednodehasbalanceFactor=0.

Figure2describesthreeAVLtreeswithtags-1,0,or+1oneachnodetoindicateitsbalance-factor(relativeheightoftheleftandrightsubtrees).

-1:

heightoftheleftsubtreeisonegreaterthantherightsubtree.

0:

heightoftheleftandrightsubtreesareequal.

+1:

heightoftherightsubtreeisonegreaterthantheleftsubtree.

FIGURE2

AVLtreeswithbalance-factorofeachnodeinparentheses

TheavlTreeNodeclassissimilartothetnodeclassforbinarysearchtrees.Fourpublicdatamembersincludethedatavalue,theleftandrightpointers,andthebalancefactor.TheconstructorisusedtocreateanodeforanAVLtreeandinitializethedatamembers.

DECLARATION:

avlTreeNodeCLASS

//declaresatreenodeobjectforabinarytree

template<

typenameT>

classavlTreeNode

{

public:

//datainthenode

TnodeValue;

//pointerstotheleftandrightchildrenofthenode

avlTreeNode<

T>

*left;

*right;

intbalanceFactor;

//CONSTRUCTOR

avlTreeNode(constT&

item,avlTreeNode<

*lptr=NULL,

avlTreeNode<

*rptr=NULL,intbal=0):

nodeValue(item),left(lptr),right(rptr),balanceFactor(bal)

{}

};

2TheavlTreeClass

TheavlTreeclasswiththesameprogrammer-interfaceusedbythestree.Theclasshasbothconstantandnon-constantiterators,whichcanbeusedtoscanthelistofelements.Anon-constantversionissuppliedsothataprogramcanusethedeferenceoperator*toupdatethedatavalueofanode.ThisfeaturecanbeusedwhentheAVLtreesstoresrecordswithakeyandotherdatavaluesandtheupdatemodifiesonlythedatavalues.Anattempttoupdatethekeycoulddestroythestructureofthetree.

LikeBinSTreeiterators,AVLiteratorsareforwarditeratorsbutwithanimportantlimitation.Sinceatreemayneedtoberebalancedwhenanitemisaddedorremoved,theinsert()anderase()operationsinvalidatealliterators.Tobeusedagain,theiteratorsmustberesettothestartofthelistwithbegin().

Thefollowingisadeclarationoftheprogrammer-interfacefortheavlTreeclass.Weimplementonlytheinsert()methodanddonotdiscusstheerase()methods.Themethodclear()isaddedtoremoveallofthenodesinthetree.Inthestreeclass,clearisexecutedbycallingerase()withtheiteratorrange[begin(),end()).ThememorymanagementfunctionsarenotincludedWewillexpandthedeclarationtoincludetheprivatememberfunctionswhenwediscusstheimplementationoftheclass.

avlTreeCLASS(Programmer-Interface

classavlTree

//CONSTRUCTORS,DESTRUCTOR,ASSIGNMENT

//constructor.initializeroottoNULLandsizeto0

avlTree();

//constructor.insertnelementsfromrangeofT*pointers

avlTree(T*first,T*last);

//searchforitem.iffound,returnaniteratorpointing

//atitinthetree;

otherwise,returnend()

iteratorfind(constT&

item);

const_iteratorfind(constT&

item)const;

//indicatewhetherthetreeisempty

intempty()const;

//returnthenumberofdataitemsinthetree

intsize()const;

//giveaverticaldisplayofthetree.

voiddisplayTree(intmaxCharacters)const;

//insertitemintothetree

//pair<

iterator,bool>

insert(constT&

//insertanewnodeusingthebasicListoperationandformat

pair<

//deleteallthenodesinthetree

voidclear();

//constantversions

iteratorbegin();

iteratorend();

const_iteratorbegin()const;

const_iteratorend()const;

ThefunctiondisplayTree()issimilartodisplayTree()inthestreeclass.Itincludesboththelabelandthebalance-factorforeachnodeintheformat<

label>

:

<

balanceFactor>

EXAMPLE1

TheexampleillustratestheuseoftheavlTreeoperations.

1.DeclareanavlTreeobjectavltreeAthatstoresintegersandanobjectavlTreeBthatstoresrealnumberswithinitialvaluesfromarrayarrB.

//avlTreeAisemptytreeofintegers

avlTree<

int>

avlTreeA;

//avlTreeBisatreeofrealswith6initialvalues

doublearrB[6]={2.8,3.9,-2.0,4.9,8.6,-12.8};

avlTree<

double>

avltreeB(arrB,arrB+6);

2.AloopinitializesavlTreeAwithintegers0to9.ThetreeisdisplayedwithdisplayTree()

for(i=1;

i<

10;

i++)

avlTreeA.insert(i);

avlTreeA.displayTree

(2);

3:

1

1:

07:

02:

05:

08:

4:

06:

09:

3.Determinewhether8.6and1.6areelementsinavlTreeB.

avlTree<

:

iteratordblIter;

if((dblIter=avlTreeB.find(8.6))!

=avlTreeB.end())

cout<

<

"

Element"

*dblIter

isanelementinAVLtree"

endl;

if((dblIter=avlTreeB.find(1.6))==avlTreeB.end())

Element1.6isnotanelementinAVLtree"

Solution:

Element8.6isanelementinAVLtree

Element1.6isnotanelementinAVLtree

3Application:

UpdatingCharacterCounts

AnAVLtreeismosteffectiveinsituationswherethedatastaticallyresidesinthetreeandtheapplicationprimarilysearchesforitemsandupdatestheirvalue.AsimpleexampledeclaresobjectsoftypecharCountthatcontainacharacteranditsfrequency(count)asdatamembers.Theclasshasaconstructorthatwithacharargumentthatinitializesthedatamemberandsetsthecountto1.Theclassalsoprovidesoverloadedversionsofthecomparisonoperators<

and==alongwithoverloadedversionofthe<

operator.ThecomparisonoperatorsallowcharCounttobeusedasthetemplatetypeforavlTreeobjectsandtheirimplementationcomparesonlyatthecharvalueoftheoperands.The<

operatoroutputsthecharacteranditscountintheform<

char>

(<

count>

).

Intheexample,wecountthenumberofoccurrencesoftheletters'

a'

to'

z'

inthe25000+worddictionary"

words.dat"

.Foreachcharacterinthedictionary,wesearchforthecorrespondingcharCountobjectandupdatethecountusingthememberfunctionincCount().

charCountCLASS

//objectcontainscharacteranditsfrequency(count)

classcharCount

//initializecharacterandcountwithcount=1

charCount(charch);

//overloadedcomparisonoperators

friendbooloperator<

(constcharCount&

a,constcharCount&

b);

friendbooloperator==(constcharCount&

//overloadedoutputandincrementoperators

friendostream&

operator<

(ostream&

ostr,constcharCount&

cc);

//incrementthecountmemberoftheobject

voidincCount();

private:

charcharacter;

intcount;

PROGRAM1COUNTINGLETTERS

TheprogramillustratestheAVLtreesearchefficiencybydeclaringanavlTree<

charCount>

objectandaniterator.Aloopinputswordsinthedictionary"

charct.dat"

asst

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 解决方案 > 商业计划

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1