A1138 Postorder Traversal (前序中序转后序)

编程入门 行业动态 更新时间:2024-10-24 06:25:26

A1138 <a href=https://www.elefans.com/category/jswz/34/1616039.html style=Postorder Traversal (前序中序转后序)"/>

A1138 Postorder Traversal (前序中序转后序)

原题:

参考柳如大佬的

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include<stack>
#include<queue>
#include<sstream>
using namespace std;/*
A1138 Postorder Traversal (25 分)
我开始以为后序第一个和中序一样,后来想想不一样
*/
const int MaxN = 50010;int pre[MaxN], in[MaxN];
int N;
vector <int> post;void ToPost(int preL, int preR, int inL, int inR) {if (preL > preR)return;//寻找in[]中的根uint u = inL;while (in[u] != pre[preL]) u++;//左右子树递归访问ToPost(preL + 1, preL + u - inL, inL, u - 1);ToPost(preL + u - inL+1, preR, u + 1, inR);post.push_back(in[u]);
}int main() {//freopen("input.txt", "r", stdin);cin >> N;for (int i = 0; i < N; i++) {cin >> pre[i];}for (int i = 0; i < N; i++)cin >> in[i];ToPost(0, N - 1, 0, N - 1);cout << post[0] << endl;return 0;}

苯办法,先建树

#include<iostream>
#include<vector>
using namespace std;
vector<int> pre, in,post;struct node {int val;struct node *left, *right;
};node* buildTree(int pl, int pr, int il, int ir) {if (pl > pr)return NULL;node *root = new node;root->val = pre[pl];root->left = root->right = NULL;int index = il;while (il <= ir && in[index] != pre[pl])index++;root->left = buildTree(pl+1, index-1-il+pl+1, il, index - 1);root->right = buildTree(pr-(ir-index-1), pr, index + 1, ir);return root;
}void dfs(node *root) {if (root == NULL)return;dfs(root->left);dfs(root->right);post.push_back(root->val);
}int main() {//readint n;cin >> n;pre.resize(n), in.resize(n);for (int i = 0; i < n; ++i)cin >> pre[i];for (int i = 0; i < n; ++i)cin >> in[i];node* root = NULL;root=buildTree(0, n - 1, 0, n - 1);dfs(root);cout << post[0] << endl;system("pause");return 0;
}

参考:

更多推荐

A1138 Postorder Traversal (前序中序转后序)

本文发布于:2024-03-05 14:20:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1712529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Postorder   前序中序转后序   Traversal

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!