1162 Postfix Expression + 递归的思想

上次遇到这种一遍过的还是在上次...

递归的思想

发现这题很符合递归的思想,站在当前层的时候,我只需要考虑如何将下一层递归返回得到的结果结合起来。再实现叶子节点这最后一层递归,递归运行的逻辑就自洽了。

PAT题目链接:https://pintia.cn/problem-sets/994805342720868352/exam/problems/1478635599577522176

题解代码:

#include<iostream>
using namespace std;
struct Node {
    string data;
    int lchild = -1, rchild = -1, fa = -1;
} g[100];
string traverse(int root) {
    if (g[root].lchild == -1 && g[root].rchild == -1) {
        // 只有叶子节点才会是数,其余都是运算
        return "(" + g[root].data + ")";
    } else if (g[root].lchild == -1) {
        return "(" + g[root].data + traverse(g[root].rchild) + ")";
    } else if (g[root].rchild == -1) {
        return "(" + g[root].data + traverse(g[root].lchild) + ")";
    } else {
        return "(" + traverse(g[root].lchild) + traverse(g[root].rchild) + g[root].data + ")";
    }
}
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        int lchild, rchild;
        cin >> g[i].data >> lchild >> rchild;
        g[i].lchild = lchild;
        g[i].rchild = rchild;
        g[lchild].fa = g[rchild].fa = i;
    }
    int root = -1;
    for (int i = 1; i <= n; i++) {
        if (g[i].fa == -1) {
            root = i;
            break;
        }
    }
    string ans = traverse(root);
    cout << ans << endl;
    return 0;
}
posted @ 2023-05-05 10:25  江韵阁  阅读(30)  评论(0)    收藏  举报