中国大学MOOC-陈越、何钦铭-数据结构-2017秋03-树3 Tree Traversals Again(25 point(s))

题目位置
本题 提示为:使用了stack进行遍历。
我们知道使用stack 遍历的最基本思想是:
从左到右,从上到下,依次遍历。
每个节点经过三次。
根据题目所给信息可以观察出来,
通过push 我们发现 这是第一次经过每个结点(如果将其pop出,为先序遍历)
通过pop发现 这是第二次经过结点,(pop出,则为中序遍历)
题目要求给出后序遍历,通过前面的发先,我们可以很容易的找到经过第三次结点时候的位置。进而实现后序遍历。

规律为【
当pop出栈顶元素时,如果是第一次pop它,则刚刚是第二次经过。如果pop的是它上一个元素,则说明经过它到达了它上一个元素,则找到了它的第三次经过的标志。估我写出了 以下代码。

代码如下,只得了21分,不知道怎么错了,如有大神,请指点一二。

#include <stdio.h>
#include <stdlib.h>
struct Stack{
    int top;
    int *data;
    int *flag;
}stack;
int main(){
    int i,j;
    int size;
    int postSequence[size+2];
    int num =0;
    scanf("%d",&size);
    stack.top=-1;
    stack.data = (int*) malloc((size+2)*sizeof(int));
    stack.flag = (int*) malloc((size+2)*sizeof(int));
    for(i=0;i<size;i++)
    {
        stack.flag[i]= 0;
    }
    char state[10];
    for(i=0;i<2*size;i++){
        scanf("%s",&state);
        if(strcmp(state,"Push")==0)stack.top++,scanf("%d",&stack.data[stack.top]);
        else{

            for(j=stack.top;j>=0;j--)
            {
                if(stack.flag[j] == 0){
                    stack.flag[j]++;
                    break;
                }
                stack.flag[j]++;
            }
        }
        while(stack.flag[stack.top] >= 2)
        {
            postSequence[num] = stack.data[stack.top];
            num++;
            stack.flag[stack.top]=0;
            stack.top--;
        }
    }
    for(i=0;i<num;i++){
        printf("%d ",postSequence[i]);
    }
    for(i=stack.top;i>0;i--)
    {
        printf("%d ",stack.data[i]);
    }
    printf("%d",stack.data[0]);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值