• PAT甲级1130Infix Expression


    题目链接

    https://pintia.cn/problem-sets/994805342720868352/problems/994805347921805312

    题解

    题目要求

    • 给定语法树,请输出其中缀表达式,用圆括号表示优先级,最后一层不要圆括号。
    • 输入
      • N:正整数,不超过20,语法树中结点的个数
      • N个结点:结点索引为[1,N],-1代表空

    解题思路

    就是二叉树的中序遍历而已,DFS就行。

    最外层不需要括号,这时手动遍历根结点即可。

    妙的是:所有结点中没有作为子结点的结点就是根结点

    代码

    // Problem: PAT Advanced 1130
    // URL: https://pintia.cn/problem-sets/994805342720868352/problems/994805347921805312
    // Tags: 二叉树 DFS
    
    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    struct Node{
        string data;
        int left = -1;
        int right = -1;
    };
    
    int n;
    vector<Node> nodes;
    
    void dfs(int root){
        if (root < 1 || root > n)
            return;
        if (nodes[root].left != -1 || nodes[root].right != -1)
            printf("(");
        dfs(nodes[root].left);
        cout << nodes[root].data;
        dfs(nodes[root].right);
        if (nodes[root].left != -1 || nodes[root].right != -1)
            printf(")");
    }
    
    int main()
    {
        scanf("%d", &n);
        nodes.resize(n+1);
        vector<bool> visited(n + 1, false);
        for (int i = 1; i <= n; i++){
            cin >> nodes[i].data;
            scanf("%d%d", &nodes[i].left, &nodes[i].right);
            if (nodes[i].left != -1)
                visited[nodes[i].left] = true;
            if (nodes[i].right != -1)
                visited[nodes[i].right] = true;
        }
        int root = 1;
        while(visited[root])
            root++;
    
        dfs(nodes[root].left);
        cout << nodes[root].data;
        dfs(nodes[root].right);
    
        return 0;
    }
    

    作者:@臭咸鱼

    转载请注明出处:https://www.cnblogs.com/chouxianyu/

    欢迎讨论和交流!


  • 相关阅读:
    测试报告M2
    11.24Daily Scrum(4)
    11.24Daily Scrum(3)
    11.24Daily Scrum(2)
    11.24Daily Scrum
    11.22Daily Scrum(2)
    11.22Daily Scrum
    Echarts中graph类型的运用求教
    Echarts学习求教
    用node编写自己的cli工具
  • 原文地址:https://www.cnblogs.com/chouxianyu/p/13749152.html
Copyright © 2020-2023  润新知