#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <queue>
#include <vector>
#define maxn 20
struct node
{
int value;
bool have_value;
node *left,*right;
node():value(0),have_value(false),left(NULL),right(NULL){}
};
using namespace std;
char s[maxn];
node *root;
bool failed;
node nodes[256];
queue<node*>pool;
void minit()
{
int i;
for(i=0;i<256;++i)
pool.push(&nodes[i]);
}
node*newnode()
{
node *a = pool.front();
pool.pop();
a -> left = a -> right = 0;
a -> have_value = false;
return a;
}
void addnode(int value,char *s)
{
int i=0,n=strlen(s);
node *u = root;
for(;i<n;++i)
{
if(s[i] == 'L')
{
if(u -> left == NULL)
u -> left = newnode();
u = u->left;
}
if(s[i] == 'R')
{
if(u -> right == NULL)
u -> right = newnode();
u = u->right;
}
}
if(u -> have_value) failed = true;
u -> value = value;
u -> have_value = true;
}
bool read_input()
{
failed = false;
root = newnode();
for(;;)
{
if(scanf("%s",s)!=1)
return false;
if(!strcmp(s,"()"))
break;
int v;
sscanf(&s[1],"%d",&v);
addnode(v,strchr(s,',')+1);
}
return true;
}
void pre_dfs(vector<int> &pre_ans,node *u) //先序
{
pre_ans.push_back(u -> value);
if(u -> left != NULL)
pre_dfs(pre_ans,u -> left);
if(u -> right != NULL)
pre_dfs(pre_ans,u -> right);
}
void in_dfs(vector<int> &in_ans,node *u) //中序
{
if(u -> left != NULL)
in_dfs(in_ans,u -> left);
in_ans.push_back(u -> value);
if(u -> right != NULL)
in_dfs(in_ans,u -> right);
}
void post_dfs(vector<int> &post_ans,node *u) 后序
{
if(u -> left != NULL)
post_dfs(post_ans,u -> left);
if(u -> right != NULL)
post_dfs(post_ans,u -> right);
post_ans.push_back(u -> value);
}
int main()
{
minit();
vector<int> pre_ans;
pre_ans.clear();
vector<int> in_ans;
in_ans.clear();
vector<int> post_ans;
post_ans.clear();
read_input();
pre_dfs(pre_ans,root);
in_dfs(in_ans,root);
post_dfs(post_ans,root);
size_t i;
for(i=0;i<pre_ans.size();++i)
printf("%d ",pre_ans[i]);
printf("\n");
for(i=0;i<in_ans.size();++i)
printf("%d ",in_ans[i]);
printf("\n");
for(i=0;i<post_ans.size();++i)
printf("%d ",post_ans[i]);
printf("\n");
return 0;
}
二叉树 DFS 先序 中序 后序