【计算机考研408】该题2017年408算法题相似度极高 PAT甲级1162 Postfix Expression

题目链接

PAT甲级1162 Postfix Expression

2017年408真题链接

2017年408真题链接

题意+题解

给你一棵语法树的基本信息。首先输入n,表示该语法树存在n个结点,接下来n行给出n个结点的信息,每行形式都为

【i行】 第i个结点的数据 第i个结点的左指针 第i个结点的右指针

根据如上要求构建出语法树,接着按要求输出

例:
在这里插入图片描述
输入

8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1

输出

(((a)(b)+)(©(-(d))))

注意:非负号可以发现都是后序遍历,只有当左子树不存在时,才会出现特殊处理

#include <bits/stdc++.h>
using namespace std;
struct node{
    
    
    string data;
    int lchild, rchild;
} tree[55];
int t[55];//用于寻找根结点

void dfs(int root, int deep){
    
    
    if (root == -1) return;
    else if (tree[root].lchild == -1 && tree[root].rchild == -1){
    
    
        cout << "(" << tree[root].data << ")";
    }
    else if (tree[root].lchild == -1 && tree[root].rchild != -1){
    
    
        if (deep > 1) cout << "(";
        cout << tree[root].data;
        dfs(tree[root].rchild, deep + 1);
        if (deep > 1) cout << ")";
    }
    else {
    
    
        if (deep > 1) cout << "(";
        dfs(tree[root].lchild, deep + 1);
        dfs(tree[root].rchild, deep + 1);
        cout << tree[root].data;
        if (deep > 1) cout << ")";
    }
}
int main(){
    
    
    int n; cin >> n;
    
    for(int i = 1; i <= n; i++){
    
    
        //string str; int l, r;  cin >> str >> l >> r;
        cin >> tree[i].data >> tree[i].lchild >> tree[i].rchild;
        t[tree[i].lchild] = t[tree[i].rchild] = 1; //说明左子树和右子树都有父节点
    }
    int root = 1;
    for(int i = 1; i <= n; i++){
    
    
        if (t[i] == 0) {
    
    
            root = i;
            break;
        }
    }
    if (n != 1) cout << "(";
    dfs(root, 1);
    if (n != 1) cout << ")";
}

猜你喜欢

转载自blog.csdn.net/qq_43382350/article/details/129328850
今日推荐