PAT(甲级)2019年秋季考试 7-3 Postfix Expression

tech2024-07-02  64

#include<cstdio> #include<iostream> #include<string> using namespace std; struct node{ string s; int left, right; }m[30]; bool vis[30]; string postT(int root) { if(m[root].left == -1 && m[root].right == -1) return "(" + m[root].s + ")"; else if(m[root].left == -1 && m[root].right != -1) return "(" + m[root].s + postT(m[root].right) + ")"; else if(m[root].left != -1 && m[root].right != -1) return "(" + postT(m[root].left) + postT(m[root].right) + m[root].s + ")"; } int main() { int n; scanf("%d", &n); for(int i = 1; i <= n; i++) { string data; cin >> m[i].s; scanf("%d%d", &m[i].left, &m[i].right); if(m[i].left != -1) vis[m[i].left] = true; if(m[i].right != -1) vis[m[i].right] = true; } int root = 1; while(vis[root] == true && root <= n) root++; string res = postT(root); cout << res << endl; }
最新回复(0)