PAT甲级-1086 Tree Traversals Again (25 分)
发布日期:2022-02-10 08:10:59 浏览次数:13 分类:技术文章

本文共 1217 字,大约阅读时间需要 4 分钟。

题目:
分析:根据二叉树的前序和中序建树,输出后序。
#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;#define MAX 999999999typedef long long ll;int n,m,k;int pre[31],in[31];int numpre, numin;struct Node{ Node* left; Node* right; int data;};Node *create(Node* root, int prel,int prer,int inl,int inr){ if(prel > prer) return NULL; if(root == NULL){ root = (Node*)malloc(sizeof(Node)); root->data = pre[prel]; root->left = NULL; root->right = NULL; } int k ; for(int i = inl;i<=inr ;i++) { if(in[i] == pre[prel]) { k = i;break; } } int num = k - inl; root->left = create(root->left, prel + 1, prel + num, inl, k - 1); root->right = create(root->right, prel + 1 + num, prer, k + 1, inr); return root;}int f ;void postT(Node *root){ if(root == NULL) return ; postT(root->left); postT(root->right); if(f == 0){ f = 1; cout<
data; } else cout<<" "<
data;}int main(){ cin>>n; stack
s; for(int i = 0; i < 2*n; i++) { string st; cin>>st; if(st == "Push"){ int x;cin>>x; s.push(x); pre[numpre++] = x; } else{ in[numin++] = s.top(); s.pop(); } } Node* root = NULL; root = create(root,0,n-1,0,n-1); postT(root); return 0;}

转载地址:https://blog.csdn.net/qq_43567222/article/details/113718736 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:PAT甲级-1085 Perfect Sequence (25 分)
下一篇:PAT甲级-1087 All Roads Lead to Rome (30 分)

发表评论

最新留言

不错!
[***.144.177.141]2024年04月14日 08时57分50秒