看别人写的键树代码看不懂,就自己写了一个。博客刚开通,就当开个张,贴一份代码上来。要下班了,改天再重新把注释说详细点,顺便把树的过程补上。#include#includeusingnamespacestd;/*因为树结构用的是左孩子-右兄弟,所以定义了移动的方向*/#defineCHILD1#defineSIBLING2#defineNOMOVE3/**树结点,左孩子-右兄弟表示法*把成员都做成public的了,主要是演示一下算法,中国自学编程网,www.zxbc.cn 。
//test.cpp:Definestheentrypointfortheconsoleapplication.
//
#include"stdafx.h"
#include<iostream>
#include<queue>
usingnamespacestd;
/*definethemovementdirection*/
#defineCHILD1
#defineSIBLING2
#defineNOMOVE3
/*
*keywordtreenode
*weuseastructureleftchild-rightsibling
*tostorethetree’snodes
*/
classknode
{
public:
knode()
{
c=0;
child=NULL;
sibling=NULL;
}
knode(intcc,knode*pc,knode*ps)
{
c=cc;
child=pc;
sibling=ps;
}
charc;
knode*child;
knode*sibling;
};
/*
*insertpatterntokeywordtree
*rootiskeywordtree’srootnode
*stristhestringinsertedtothetree
*/
voidinsertKTree(knode*constroot,char*str)
{
knode*troot=root;
knode*tproot=root;/*savethepreviousnodewhenmoveinthetree*/
troot=root->child;
intmoveDir=NOMOVE;
/*
findthematchedportionofsubstringinstrassoonaspossiable,
meanwhile,movethepointerstr.
*/
while(troot!=NULL)
{
if(troot->c==*str) [Page]
{
str++;
tproot=troot;
troot=troot->child;
moveDir=CHILD;/*movetochild*/
}
else
{
tproot=troot;
troot=troot->sibling;
moveDir=SIBLING;/*movetosibling*/
}
}
/*readytoinsertthereststringpointedtobystrintothetree*/
switch(moveDir)
{
caseNOMOVE:/*treeonlyhasanode(rootnode)*/
caseCHILD:/*insertnodeaschild*/
while(*str!=’