用树状树组存树根据树的前中后序遍历思想递归建树
前序:
void dfs(int i){
if(i>n)
return;
nodes[i]=arr[cnt];
cnt++;
if(i*2<=n){
dfs(i*2);
}
if(i*2+1<=n){
dfs(i*2+1);
}
}
中序:
void dfs(int i){
if(i>n)
return;
if(i*2<=n){
dfs(i*2);
}
nodes[i]=arr[cnt];
cnt++;
if(i*2+1<=n){
dfs(i*2+1);
}
}
后序:
#include<bits/stdc++.h>
using namespace std;
const int N = 35;
int arr[N];
int nodes[N];
int n;
int cnt = 1;
void dfs(int i){
if(i>n)
return;
if(i*2<=n){
dfs(i*2);
}
if(i*2+1<=n){
dfs(i*2+1);
}
nodes[i]=arr[cnt];
cnt++;
}
void solve(){
cin>>n;
for(int i =1;i<=n;i++)cin>>arr[i];
dfs(1);
for(int i =1;i<=n;i++)
{
if(i!=n)
cout<<nodes[i]<<" ";
else
cout<<nodes[i];
}
}
signed main()
{
// ios::sync_with_stdio(0);
// cin.tie(0);
// cout.tie(0);
int __ = 1;
//cin>>__;
while (__--) {
// init();
solve();
}
}