Home PAT 1162 Postfix Expression
Post
Cancel

PAT 1162 Postfix Expression

Link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
int n;
bool v[25];
struct node{
    char data[15];
    int left,right;
}a[25];
void PostOrder(int x){
    if(a[x].left==-1){
        printf("%s",a[x].data);
        if(a[x].right!=-1){
            printf("(");
            PostOrder(a[x].right);
            printf(")");
        }
    }else{
        printf("(");
        PostOrder(a[x].left);
        printf(")");
        if(a[x].right!=-1){
            printf("(");
            PostOrder(a[x].right);
            printf(")");
        }
        printf("%s",a[x].data);
    }
}
int main() {
    scanf("%d",&n);
    for(int i=1;i<=n;++i){
        scanf("%s%d%d",a[i].data,&a[i].left,&a[i].right);
        if(a[i].left!=-1) v[a[i].left]=true;
        if(a[i].right!=-1) v[a[i].right]=true;
    }
    int root=0;
    for(int i=1;i<=n;++i)
        if(!v[i]){
            root=i;
            break;
        }
    printf("(");
    PostOrder(root);
    printf(")");
    return 0;
}
This post is licensed under CC BY 4.0 by the author.