PAT 1086 Tree Traversal Again

采用二叉树的数组表示方法,用stack保存一下当前节点编号,每push一下都将当前节点编号*2转向左子树,pop的时候就pop出来转向右子树。
#include <stdio.h>
#include <algorithm>
#include <stack>
#include <string.h>
using namespace std;
int n,k,current=1;
int Tree[10000];
int flag=0;
char op[2][10]={"Push","Pop"};
stack<int>s;
void postorder(int root){
    if (Tree[root*2]!=-1) postorder(root*2);
    if (Tree[root*2+1]!=-1) postorder(root*2+1);
    if (flag==0){
        flag=1;
        printf("%d",Tree[root]);
    }
    else
        printf(" %d",Tree[root]);
}
int main(){
    //freopen("/Users/pantingting/Documents/code/data/input", "r", stdin);
    memset(Tree, 0xff, sizeof(Tree));
    scanf("%d",&n);
    char tempop[10];
    for (int i=0; i<2*n; i++) {
        scanf("%s",tempop);
        if (strcmp(tempop, op[0])==0) {
            scanf("%d",&k);
            Tree[current]=k;
            s.push(current);
            current*=2;
            continue;
        }
        if (strcmp(tempop, op[1])==0) {
            int temp=s.top();
            s.pop();
            current=temp*2+1;
        }
    }
    postorder(1);
    printf("\n");
    return  0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值