PAT甲级-1086 Tree Traversals Again (25 分)

题目:1086 Tree Traversals Again (25 分)
分析:根据二叉树的前序和中序建树,输出后序。
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#include<iostream>
using namespace std;
#define MAX 999999999
typedef 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<<root->data;
    }
    else
        cout<<" "<<root->data;
}
int main()
{
    cin>>n;
    stack<int>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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值