编程离不开算法,算法离不开数据结构,数据结构里最重要的非线性结构便是树了,树原本是特殊的图,但我们不在图论里讨论树,就是因为其非常特殊,所以我们
一般都是单独讨论,下面我先说一下一般树的实现:
对于一般的树,即n叉树,我们一般是用先大儿子再兄弟的表示方法把n叉树用二叉树来表示,这种树也是很有实际应用的,例如表达式树的建立,还有文件目录树的建立等等
,而这种树的遍历同样也是有前序遍历,中序遍历和后序遍历三种方法,下面就是我的c++代码实现:
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
template<class obj_s>
class tree{
public:
struct treenode
{
obj_s ele;
treenode *firstchild;
treenode *nextsibling;
treenode(obj_s x,treenode *f=NULL,treenode *n=NULL)
:ele(x),firstchild(f),nextsibling(n){}
};
treenode *root;
void clear(treenode * & t){
if(t!=NULL)
{
clear(t->firstchild);
clear(t->nextsibling);
delete t;
}
t=NULL;
}
tree(){root=NULL;}
tree(const tree & T){*this=T;}
~tree(){clear(root);}
tree & operator =(const tree &T)
{
if(this!=&T)
{
clear(root);
root=clone(T.root);
}
return *this;
}
treenode *clone(treenode *t)
{
if(t==NULL)
return NULL;
return new treenode(t->ele,clone(t->firstchild),clone(t->nextsibling));
}
friend istream & operator >>(istream &is,treenode *&t)
{
obj_s x;
cin>>x;
if(x!="\\")
{ t=new treenode(x,NULL,NULL);
is>>t->firstchild;
is>>t->nextsibling;
}
return is;
}
// treenode * Root(){return this->root;}
void display1(treenode *p,int n=0)
{
if(p!=NULL)
{ for(int i=0;i<n;i++)
cout<<" ";
cout<<p->ele<<endl;
display1(p->firstchild,n+1);
display1(p->nextsibling,n);
}
}
void display2(treenode *p,int n=0)
{
if(p!=NULL)
{ display2(p->firstchild,n+1);
for(int i=0;i<n;i++)
cout<<" ";
cout<<p->ele<<endl;
display2(p->nextsibling,n);
}
}
void display3(treenode *p,int n=0)
{
if(p!=NULL)
{ display3(p->firstchild,n+1);
display3(p->nextsibling,n);
for(int i=0;i<n;i++)
cout<<" ";
cout<<p->ele<<endl;
}
}
};
int main(){
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
tree<string> T;
while(cin>>T.root)
{
cout<<"前序遍历的结果为:" <<endl;
T. display1(T.root);
cout<<"中序遍历的结果为:" <<endl;
T. display2(T.root);
cout<<"后序遍历的结果为:" <<endl;
T. display3(T.root);
}
fclose(stdin);
fclose(stdout);
return 0;
}
然后是in.txt的数据:
A B \ C \ D H \ \ E I \ J P \ Q \ \ \ F K \ L \ M \ \ G N \ \ \ \
/usr
mark
book
ch1.r
\
ch2.r
\
ch3.r
\
\
course
cop3530
fall05
syl.r
\
\
spr06
syl.r
\
\
sum06
syl.r
\
\
\
\
junk
\
\
alex
junk
\
\
bill
work
\
course
cop3212
fall05
grades
\
prog1.r
\
prog2.r
\
\
fall06
prog2.r
\
prog1.r
\
grades
\
\
\
\
\
\
\
最后是out.txt的结果:
前序遍历的结果为:
A
B
C
D
H
E
I
J
P
Q
F
K
L
M
G
N
中序遍历的结果为:
B
C
H
D
I
P
Q
J
E
K
L
M
F
N
G
A
后序遍历的结果为:
H
Q
P
J
I
M
L
K
N
G
F
E
D
C
B
A
前序遍历的结果为:
/usr
mark
book
ch1.r
ch2.r
ch3.r
course
cop3530
fall05
syl.r
spr06
syl.r
sum06
syl.r
junk
alex
junk
bill
work
course
cop3212
fall05
grades
prog1.r
prog2.r
fall06
prog2.r
prog1.r
grades
中序遍历的结果为:
ch1.r
ch2.r
ch3.r
book
syl.r
fall05
syl.r
spr06
syl.r
sum06
cop3530
course
junk
mark
junk
alex
work
grades
prog1.r
prog2.r
fall05
prog2.r
prog1.r
grades
fall06
cop3212
course
bill
/usr
后序遍历的结果为:
ch3.r
ch2.r
ch1.r
syl.r
syl.r
syl.r
sum06
spr06
fall05
cop3530
junk
course
book
junk
prog2.r
prog1.r
grades
grades
prog1.r
prog2.r
fall06
fall05
cop3212
course
work
bill
alex
mark
/usr