题目

思路
把这个顺序储存变成链式储存再进行后序遍历(先左子树,然后右子树,再根节点)
前中后遍历介绍
由于不知道是几叉树,所以交给万能的STL了就不自己搞链树了
代码
#include<bits\stdc++.h>
using namespace std;
int Count = 0;
void Postorder(int n, vector<int>* tree)
{
for(int i = 0; i < tree[n].size(); i++)
{
Postorder(tree[n][i], tree);
}
cout << (Count++ ? " " : "") << n;
}
int main()
{
int n; cin >> n;
vector<int> tree[10000];
for(int i = 0; i < n; i++)
{
int parent;
cin >> parent;
if(parent != -1)
tree[parent].push_back(i);//转化成链式树
}
Postorder(0, tree);
}
该篇博客主要介绍了如何使用链式存储来实现树的后序遍历。通过将树的顺序储存转化为链式储存,然后进行后序遍历(先左子树,再右子树,最后根节点)。文章提供了C++代码实现,利用STL简化了多叉树的处理。在main函数中,读取树的结构并调用后序遍历函数,输出遍历结果。
1857





