AVLTREES文档格式.docx
《AVLTREES文档格式.docx》由会员分享,可在线阅读,更多相关《AVLTREES文档格式.docx(21页珍藏版)》请在冰豆网上搜索。
![AVLTREES文档格式.docx](https://file1.bdocx.com/fileroot1/2022-11/27/e586bd6d-e079-4d2e-be71-62db00e541e4/e586bd6d-e079-4d2e-be71-62db00e541e41.gif)
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