PAT甲级 1086 Tree Traversals Again (二叉树遍历+一个转弯)

思路

唯一二叉树的建立必须需要中序序列+前序/后序/层次遍历,在题目里面找。这里实在不好看出来。就尝试着把入栈序列出栈序列写出来看看有没有突破口叭。

入栈序列即是前序遍历,出栈序列即是中序遍历

写题历程

在这里插入图片描述

代码

#include <iostream>
#include<cstdio>
#include<map>
#include<queue>
#include<string>
#include<algorithm>
#include<vector>
#include<cmath>
#include<stack>
#include<cstring>

using namespace std;

const int maxn = 30;
int n, precnt = 0, incnt = 0, flag = 0;
int pre[maxn+5], in[maxn+5];
stack<int> values;

struct node{
    int data;
    node* left;
    node* right;
};


node* create(int preL, int preR, int inL, int inR){
    if(preL > preR)
        return NULL;

    node* root = new node;
    root->data = pre[preL];

    int k;
    for(int i = 0; i < n; i++){
        if(in[i] == pre[preL]){
            k = i;
            break;
        }
    }

    int numLeft = k - inL;//左子树节点个数时k - inL而不是k - preL
    root->left = create(preL + 1, preL + numLeft, inL, k-1);
    root->right = create(preL + 1 + numLeft, preR, k+1, inR);

    return root;//没有输出是因为忘记返回rootL !
}

void postTravel(node* root){
    //边界条件返回
    if(root == NULL) return;

    postTravel(root->left);
    postTravel(root->right);

    if(flag) printf(" ");
    flag = 1;
    printf("%d", root->data);
}

int main(){
    scanf("%d", &n);
    getchar();
    for(int i = 0; i < 2*n; i++){
        char str[5];
        scanf("%s", str);
        //Push
        if(strcmp(str, "Push") == 0){
            int numValue;
            scanf("%d", &numValue);
            values.push(numValue);
            pre[precnt++] = numValue;
        }else{//pop
            in[incnt++] = values.top();
             values.pop();
        }
    }

    node* root = create(0, n-1, 0, n-1);

    postTravel(root);

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值