包含前、中、后、层次遍历
#include <bits/stdc++.h>
using namespace std;
queue<int> q;
const int N = 110;
int idx,l[N],r[N];
char w[N];
int root;
void insert(int &root)
{
char x;
cin >> x;
if(x == '#') root = 0;
else
{
root = ++idx,w[root] = x;
insert(l[root]);
insert(r[root]);
}
}
void dfs(int root,int t)
{
if(!root) return;
if(t == 0)
cout << w[root] << " ";
dfs(l[root],t);
if(t == 1)
cout << w[root] << " ";
dfs(r[root],t);
if(t == 2)
cout << w[root] << " ";
}
void Typeshow(int u)
{
if(u == 0) return;
q.push(root);
while(q.size() > 0)
{
int bt = q.front();
cout << w[bt] << " ";
q.pop();
if(l[bt]!= 0)
q.push(l[bt]);
if(r[bt]!= 0)
q.push(r[bt]);
}
}
int main()
{
insert(root);
for(int i = 0; i < 3; i++)
{
dfs(root,i);
cout <<endl;
}
Typeshow(root);
}
//输入样例
//abc##d##e#f##
//输出样例
//pre_order:a b c d e f
//mid_order:c b d a e f
//post_order:c d b f e a
//quene_order:a b e c d f