第二天PAT-A1102 Invert a Binary Tree

A1086

Description:

一个中序二叉树序列可用一个栈以非递归的方式实现。

栈输出序列:324165

入栈顺序:123456(先序)

详细见A1020

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
#include<stack>
using namespace std;

const int maxn = 35;
struct node{
    int left;
    int right;
}Node[maxn];
stack<int>st;
int in[maxn], pre[maxn], post[maxn], inpost=1;    //中序,先序,后序
map<int, int>inmap;
map<int, int>premap;
int n, num;
char op[5];

int create(int inL, int inR, int preL, int preR){
    if(preL > preR)
        return -1;
    int root = pre[preL];
    int lnum = inmap[root] - inL;
    int rnum = inR - inmap[root];
    Node[root].left = create(inL, inL+lnum-1, preL+1, preL+lnum);
    Node[root].right = create(inR-rnum+1, inR, preL+lnum+1, preR);
    return root;
}

void postOrder(int root){
    if(Node[root].left != -1) postOrder(Node[root].left);
    if(Node[root].right != -1) postOrder(Node[root].right);
    post[inpost++] = root;
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d", &n);
    int prein = 1, inin = 1;
    for(int i = 0; i < 2*n; i++){
        scanf("%s", op);
        if(strcmp(op, "Push")){
            inmap.insert(pair<int, int>(st.top(), inin));
            in[inin++] = st.top();
            st.pop();
        }
        else{
            scanf("%d", &num);
            premap.insert(pair<int, int>(num, prein));
            pre[prein++] = num;
            st.push(num);
        }
    }
    memset(Node, -1, sizeof(Node));
    int root = create(1, n, 1, n);
    postOrder(root);
    for(int i = 1; i < inpost; i++){
        if(i != 1)
            printf(" ");
        printf("%d", post[i]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值