关于树的先序遍历,层次遍历,后序遍历


// 已知后序遍历和中序遍历,求层次遍历





#include<iostream> #include<cstdio> #include<vector> #include<algorithm> #include<map> using namespace std; #define STDIN freopen("in.txt", "r", stdin);freopen("out.txt", "w", stdout); const int N = 35; int in[N], post[N]; vector<pair<int,int> > vec; bool cmp(pair<int,int> a, pair<int, int> b) { return a.second < b.second; } void level_order(int root, int start, int end, int index) { if (start > end) return ; int i = start; while (i < end && in[i] != post[root]) i++; // cout << post[root] << " " << index << endl; vec.push_back({post[root], index}); level_order(root - (end - i + 1), start, i-1, 2*index); level_order(root-1, i + 1, end, 2*index + 1); } int main() { // STDIN int n; cin >> n; for (int i = 1; i <= n; i++) cin >> post[i]; for (int i = 1; i <= n; i++) cin >> in[i]; level_order(n,1,n,1); sort(vec.begin(), vec.end(), cmp); int len = vec.size(); for(int i = 0; i < len; i++) { printf("%d%c", vec[i], " \n"[i == len-1]); } }

 

posted @ 2020-10-26 19:36  hulian425  阅读(174)  评论(0编辑  收藏  举报