1086 Tree Traversals Again (25)

//给定先序中序,求后序
//code:
#include <cstdio>
#include <cstring>
#include <stack>
#include <iostream>
using namespace std;
const int MAXN = 35;
struct node{
    int data;
    node* lChild;
    node* rChild;
};
int N;
int preOrder[MAXN], inOrder[MAXN];
node* create(int preL, int preR, int inL, int inR) {
    if(preL > preR) return NULL;
    node* root = new node;
    root->data = preOrder[preL];
    int k;
    for(k=0; k<N; k++)
        if(preOrder[preL] == inOrder[k])
            break;
    int numLeft = k - inL;
    root->lChild = create(preL+1, preL+numLeft, inL, inL+numLeft-1);
    //或create(preL+1, preL+numLeft, inL, k-1);
    root->rChild = create(preL+numLeft+1, preR, inL+numLeft+1, inR);
    //或create(preL+numLeft+1, preR, k+1, inR);
    return root;
}
int j = 1;
void dfs(node* root) {
    if(root == NULL) return;
    dfs(root->lChild);
    dfs(root->rChild);
    if(j != N){
        printf("%d ",root->data);
        j++;
    } else printf("%d",root->data);
}
int main() {
    scanf("%d",&N);
    stack<int> s;
    char how[5];
    int x;
    int j_1 = 0, j_2 = 0;
    for(int i=0; i<N*2; i++) {
        scanf("%s",how);
        if(strcmp(how, "Push") == 0) {
            scanf("%d",&x);
            preOrder[j_1++] = x;
            s.push(x);
        } else {
            inOrder[j_2++] = s.top();
            s.pop();
        }
    }
    node* root = create(0, N-1, 0, N-1);
    dfs(root);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值