Home PAT 1130 Infix Expression
Post
Cancel

PAT 1130 Infix 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
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
int n;
struct node{
    string data;
    int left=-1,right=-1;
}tree[25];
bool v[25];
void InOrder(int root){
    if(tree[root].left!=-1){
        if(tree[tree[root].left].left!=-1||tree[tree[root].left].right!=-1){
            cout<<"(";
            InOrder(tree[root].left);
            cout<<")";
        }else InOrder(tree[root].left);
    }
    cout<<tree[root].data;
    if(tree[root].right!=-1){
        if(tree[tree[root].right].left!=-1||tree[tree[root].right].right!=-1){
            cout<<"(";
            InOrder(tree[root].right);
            cout<<")";
        }else InOrder(tree[root].right);
    }
}
int main() {
    cin>>n;
    for(int i=1;i<=n;++i){
        cin>>tree[i].data>>tree[i].left>>tree[i].right;
        if(tree[i].left!=-1) v[tree[i].left]=true;
        if(tree[i].right!=-1) v[tree[i].right]=true;
    }
    int root=0;
    for(int i=1;i<=n;++i)
        if(!v[i]){
            root=i;
            break;
        }
    InOrder(root);
    printf("\n");
    return 0;
}
This post is licensed under CC BY 4.0 by the author.