#include<iostream>
#include<stack>
using namespace std;
//二叉树数据结构
typedef struct TreeNode
{
char data;
struct TreeNode *Leftchild;
struct TreeNode *Rightchild;
TreeNode(char c)
{
data=c;
Leftchild=NULL;
Rightchild=NULL;
}
} TreeNode,*Tree;
//创建二叉树
void CreateTree(Tree &p)
{
char c;
cin>>c;
if(c=='#') p=NULL;
else
{
p=new TreeNode(c);
cout<<"请输入"<<p->data<<"的左子树: ";
CreateTree(p->Leftchild);
cout<<"请输入"<<p->data<<"的右子树: ";
CreateTree(p->Rightchild);
}
}
//先序遍历
void PreOrder(Tree &T)
{
stack<Tree> S;
Tree p=T;
while(p||!S.empty())
{
if(p)
{
cout<<p->data<<" ";
S.push(p);
p=p->Leftchild;
}
else
{
p=S.top()->Rightchild;
S.pop();
}
}
}
//中序遍历
void InOrder(Tree &T)
{
stack<Tree> S;
Tree p=T;
while(p||!S.empty())
{
if(p)
{
S.push(p);
p=p->Leftchild;
}
else
{
p=S.top();
cout<<p->data<<" ";
p=p->Rightchild;
S.pop();
}
}
}
//后序遍历
void PostOrder(Tree &T)
{
Tree p=T;
stack<Tree> S;
stack<char> SS;
while(p||!S.empty())
{
if(p)
{
SS.push(p->data);
S.push(p);
p=p->Rightchild;
}
else
{
p=S.top()->Leftchild;
S.pop();
}
}
while(!SS.empty())
{
cout<<SS.top()<<" ";
SS.pop();
}
}
int main()
{
Tree p=NULL;
cout<<"创建二叉树,请输入根节点(#表示节点为空): ";
CreateTree(p);
cout<<"先序遍历: ";
PreOrder(p);
cout<<endl;
cout<<"中序遍历: ";
InOrder(p);
cout<<endl;
cout<<"后序遍历: ";
PostOrder(p);
return 0;
}
05-05
3974
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-22
02-07
2699
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-09
9642
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)