题目描述
完全二叉树适合采用顺序存储法。具体存储规则如下(一维数组存储法):
1. 根节点的下标为1
2. 若某结点的下标为 i,则其左孩子位于下标 2i 处、右孩子位于下标 2i+1 处
现在读入一个顺序存储法的完全二叉树,输出对应的前序,中序,后续遍历。
输入
先读入一个n
再读入n个整数, 数量小于等于10000
输出
输出对应的前序,中序,后续遍历,每个遍历一行。
样例输入
7
1 2 3 4 5 6 7
样例输出
1 2 4 5 3 6 7
4 2 5 1 6 3 7
4 5 2 6 7 3 1
#include <bits/stdc++.h>
using namespace std;
int s[10010];
int n;
void dfs1(int now){
int a=2*now;
int b=2*now+1;
cout<<s[now]<<" ";
if(a<=n)dfs1(a);
if(b<=n)dfs1(b);
}
void dfs2(int now){
int a=2*now;
int b=2*now+1;
if(a<=n)dfs2(a);
cout<<s[now]<<" ";
if(b<=n)dfs2(b);
}
void dfs3(int now){
int a=2*now;
int b=2*now+1;
if(a<=n)dfs3(a);
if(b<=n)dfs3(b);
cout<<s[now]<<" ";
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)cin>>s[i];
dfs1(1);cout<<"\n";
dfs2(1);cout<<"\n";
dfs3(1);
}