#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;
struct BiNode
{
char data;
struct BiNode *left;
struct BiNode *right;
};
typedef struct BiNode Node;
typedef Node* LinkNode;
//以先序的顺序编写结点
LinkNode CreatTree(LinkNode T)
{
char temp;
cin>> temp;
if('0' == temp)
{
T = NULL;
}
else
{
T = (LinkNode)malloc(sizeof(Node));
T->data = temp;
T->left = CreatTree(T->left);
T->right = CreatTree(T->right);
}
return T;
}
//非递归前序
void PreOrder(LinkNode T)
{
if(T == NULL)
{
return;
}
vector<LinkNode> s;
LinkNode p = T;
while(p != NULL || !s.empty())
{
while(p != NULL)
{
cout<<p->data;
s.push_back(p);
p = p ->left;
}
if(!s.empty())
{
p = s[s.size()-1];
s.pop_back();
p = p->right;
}
}
}
void InOrder(LinkNode T)
{
if(NULL == T)
{
return;
}
vector<LinkNode> s;
LinkNode p = T;
while(p != NULL || !s.empty())
{
while(p != NULL)
{
s.push_back(p);
p = p->left;
}
if(!s.empty())
{
p= s[s.size()-1];
cout<<p->data;
s.pop_back();
p = p->right;
}
}
}
/*
具体思路:栈S1 和S2 。首先根节点入栈S1,当S1不为空弹出栈顶元素,并入栈S2,如果说弹出的左右子树不为空,则依次将其左子树和右子树入栈。直到栈S1空时停止。/i/
*/
void PostOrder(LinkNode T)
{
if(NULL == T)
{
return;
}
vector<LinkNode> s1,s2;
LinkNode p = T;
s1.push_back(T);
while(!s1.empty())
{
p = s1[s1.size()-1];
s1.pop_back();
s2.push_back(p);
if(p->left != NULL)
{
s1.push_back(p->left);
}
if(p->right != NULL)
{
s1.push_back(p->right);
}
}
while(!s2.empty())
{
p = s2[s2.size()-1];
cout<<p->data;
s2.pop_back();
}
}
int main()
{
Node *Tree;
Tree = CreatTree(Tree);
cout<<"前序序列:"<<endl;
PreOrder(Tree);
cout<<endl;
cout<<"中序序列:"<<endl;
InOrder(Tree);
cout<<endl;
cout<<"后序序列:"<<endl;
PostOrder(Tree);
cout<<endl;
}
运行结果