因为只要过了数据就行,本博文不采用上述填空形式(链表太繁琐了,不利于记忆
本博文采用数组模拟树的思路,代码更清晰
数组模拟二叉树有性质:假设结点编号为p,左儿子编号为2*p,右儿子编号为2*p+1,就可以模拟树了
递归建树,三种遍历其实代码相差无几,只要改变一下输出根结点的位置即可
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(0)
#define _for(i,a,b) for(int i=(a) ;i<=(b) ;i++)
#define _rep(i,a,b) for(int i=(a) ;i>=(b) ;i--)
#define mst(x,y) memset(x,y,sizeof(x))
#define all(v) v.begin() , v.end()
#define pb(v) push_back(v)
#define INF 0x3f3f3f3f
#define int long long
#define lson p*2,l,mid
#define rson p*2+1,mid+1,r
typedef long long ll;
const int N = 1e5+10;
char s1[N];
int len1;//输入字符串长度
int n;
int num=0;
char tree[N];//数组存树
void build(int pos)//递归建树
{
num++;
if( num > len1) return ;//递归边界,输入字符读取完毕
if( s1[num] == '#')//建树边界
{
return;
}
//根据根左右的顺序建树
tree[pos] = s1[num];//当前结点赋值
build(pos*2);//建左子树
build(pos*2+1);//建右子树
}
void xian(int pos)//先序遍历,(其实把输入字符串删掉#就可以了
{
if( tree[pos] =='\0') return;
//根左右递归
cout<<tree[pos];
xian(pos*2);
xian(pos*2+1);
}
void zhong(int pos)
{
if( tree[pos] == '\0' ) return;
//左根右递归
zhong(pos*2);
cout<<tree[pos];
zhong(pos*2+1);
}
void hou(int pos)
{
if( tree[pos] == '\0' ) return;
//左右根递归
hou(pos*2);
hou(pos*2+1);
cout<<tree[pos];
}
void solve()
{
build(1);
xian(1);
cout<<endl;
zhong(1);
cout<<endl;
hou(1);
cout<<endl;
}
signed main()
{
//!!!!!!!!!!!!!!!!!!!!!!
// freopen("data.txt","r",stdin);
//!!!!!!!!!!!!!!!!!!!!!!
IOS;
cin>>(s1+1);
len1 = strlen(s1+1);
solve();
}