PAT 1086 Tree Traversals Again (25分)

PAT 1086 Tree Traversals Again

问题简述

给出先序与中序,要求你给出后序遍历的序列

代码-C

其中一个小报错Variably modified array at file scope;在C中数组大小似乎不支持const 类型表示,
那改为宏吧
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 50
// const int maxn = 50;

typedef struct node{
    int data;
    struct node* lc;
    struct node* rc;
}node;
typedef struct Stack
{
    int top;
    int data[maxn];
}Stack;
Stack st;
void st_init()
{
    st.top = -1;
    memset(st.data, 0, maxn);
}
void st_push(int val)
{
    st.data[++st.top] = val;
}
void st_pop()
{
    st.data[st.top--] = 0;
}
int st_top()
{
    return st.data[st.top];
}

int pre[maxn], post[maxn], in[maxn];
int n, num = 0;
node* Create(int preL, int preR, int inL, int inR)
{
    if(preL > preR)
        return NULL;
    node* root = (node*) malloc(sizeof(node));
    root->data = pre[preL];
    int k;
    for(k = inL; k <= inR; k++)
    {
        if(in[k] == pre[preL])
            break;
    }
    int numLeft = k - inL;
    root->lc = Create(preL + 1, preL + numLeft, inL, k-1);
    root->rc = Create(preL + numLeft + 1, preR, k + 1, inR);
    return root;
}

void postOrder(node* root)
{
    if(root == NULL)
        return;
    postOrder(root->lc);
    postOrder(root->rc);
    printf("%d", root->data);
    num++;
    if(num < n)
        printf(" ");
}

int main()
{
    st_init();
    scanf("%d", &n);
    char str[5];
    int x, preIndex = 0, inIndex = 0;
    for(int i = 0; i < 2 * n; i++)
    {
        scanf("%s", str);
        if(strcmp(str, "Push") == 0)
        {
            scanf("%d", &x);
            pre[preIndex++] = x;
            st_push(x);
        }
        else
        {
            in[inIndex++] = st_top();
            st_pop();
        }
    }
    node *root = Create(0, n-1, 0, n-1);
    postOrder(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值