题意
给你n个节点数,并给出后序遍历的序列
思路
1.输入所有点后,按后序遍历(左右根)的方法,标记点的位置即可。
2.后续遍历就是回溯操作
坑点
无
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 50;
int a[N], tree[N];
int n;
int idx = 1;
void dfs(int u)//当前根节点
{
if (u > n) return;
dfs(u * 2);//左边的子节点
dfs(u * 2 + 1);//右边的子节点
tree[u] = a[idx ++];//层序的对应
}
int main()
{
cin >> n;//n个节点
for (int i = 1; i <= n; i ++ )
{
cin >> a[i];//读入各个节点的对应的值
}
dfs(1);//从1开始搜索
for (int i =1; i <= n; i ++ )
{
cout << tree[i];//输出层序的排列
if (i != n) cout << " ";//注意格式,最后一个数后没有空格
}
return 0;
}
总结
难度中等,需熟练掌握后序遍历