#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef char TElemType;
typedef struct TreeNode
{
TElemType data;
struct TreeNode *left;
struct TreeNode *right;
}Treenode;
typedef struct SNode
{
int no;
Treenode *node;
}StackNode;
int n,min1;
Treenode* buildTree()
{
char x;
scanf("%c",&x);
if(x=='#')
{
return NULL;
}
else
{
Treenode*p=(Treenode*)malloc(sizeof(Treenode));
p->data=x;
p->left=buildTree();
p->right=buildTree();
return p;
}
};
//链式前序遍历
int pre( Treenode *p)
{
printf("%c ",p->data);
if(p->left!=NULL)
pre(p->left);
if(p->right!=NULL)
pre(p->right);
return 0;
}
//链式中序遍历
int in( Treenode *p)
{
if(p->left!=NULL)
in(p->left);
printf("%c ",p->data);
if(p->right!=NULL)
in(p->right);
return 0;
}
//链式后序遍历
int aft( Treenode *p)
{
if(p->left!=NULL)
aft(p->left);
if(p->right!=NULL)
aft(p->right);
printf("%c ",p->data);
return 0;
}
//非递归前序遍历
int pre1(Treenode *p)
{
stack<Treenode*> s;
while(!s.empty()||p)
{
if(p)
{
printf("%c ",p->data);
s.push(p);
p=p->left;
}
else
{
p=s.top();
s.pop();
p=p->right;
}
}
}
//非递归中序遍历
int in1(Treenode *p)
{
stack<Treenode*> s;
while(!s.empty()||p)
{
if(p)
{
s.push(p);
p=p->left;
}
else
{
p=s.top();
printf("%c ",p->data);
s.pop();
p=p->right;
}
}
}
//非递归后序遍历
int aft1(Treenode *p)
{
stack<StackNode> s;
while(!s.empty()||p)
{
if(p)
{
StackNode t;
t.no=1;
t.node=p;
s.push(t);
p=p->left;
}
else
{
StackNode t=s.top();
if(t.no==1)
{
p=t.node->right;
t.no=2;
s.pop();
s.push(t);
}
else
{
t=s.top();
s.pop();
printf("%c ",t.node->data);
}
}
}
}
int main()
{
int x,y;
Treenode *h;
h=buildTree();
printf("先序遍历:");
pre(h);
printf("\n");
printf("中序遍历:");
in(h);
printf("\n");
printf("后序遍历:");
aft(h);
//非递归操作
printf("\n\n非递归:");
printf("\n非递归先序遍历:");
pre1(h);
printf("\n非递归中序遍历:");
in1(h);
printf("\n非递归后序遍历:");
aft1(h);
return 0;
}