#include<iostream>
using namespace std;
class tree
{
public:
char data;
class tree *lchild;
class tree *rchild;
};
void build(tree *&t)//先序建树
{
char c;
cin>>c;
if(c=='#')
{
t=NULL;
}
else
{
t=new tree;
t->data=c;
build(t->lchild);
build(t->rchild);
}
}
void preorder(tree *t)//先序递归遍历
{
if(t)
{
cout<<t->data;
preorder(t->lchild);
preorder(t->rchild);
}
}
void inorder(tree *t)//中序递归遍历
{
if(t)
{
inorder(t->lchild);
cout<<t->data;
inorder(t->rchild);
}
}
void postorder(tree *t)//后序递归遍历
{
if(t)
{
postorder(t->lchild);
postorder(t->rchild);
cout<<t->data;
}
}
int main()
{
tree *t=new tree;
cout<<"先序建树"<<endl;
build(t);
cout<<"先序递归遍历"<<endl;
preorder(t);
cout<<endl<<"中序递归遍历"<<endl;
inorder(t);
cout<<endl<<"后序递归遍历"<<endl;
postorder(t);
cout<<endl;
return 0;
}
二叉树的建立与递归遍历C++版
最新推荐文章于 2024-04-21 12:08:44 发布