PAT_A1130#Infix Expression
Source:
Description:
Input Specification:
Output Specification:
Sample Input 1:8 * 8 7 a -1 -1 * 4 1 + 2 5 b -1 -1 d -1 -1 - -1 6 c -1 -1 Sample Output 1:(a+b)*(c*(-d)) Sample Input 2:8 2.35 -1 -1 * 6 1 - -1 4 % 7 8 + 2 3 a -1 -1 str -1 -1 871 -1 -1 Sample Output 2:(a*2.35)+(-(str%871)) Keys:
Code:1 /* 2 Data: 2019-07-04 14:51:54 3 Problem: PAT_A1130#Infix Expression 4 AC: 16:51 5 6 题目大意: 7 打印中缀表达式 8 输入: 9 第一行给出,结点个数N<=20 10 接下来N行,给出结点i(1~N)的,键值,左孩子编号,右孩子编号(空子树-1) 11 12 基本思路: 13 静态树存储,输出中缀表达式 14 */ 15 #include<cstdio> 16 #include<string> 17 #include<map> 18 #include<iostream> 19 using namespace std; 20 const int M=25; 21 struct node 22 { 23 string data; 24 int lchild,rchild; 25 }tree[M]; 26 map<int,int> mp; 27 28 void DFS(int root,int layer) 29 { 30 if(root==-1) 31 return; 32 else if(tree[root].lchild==-1 && tree[root].rchild==-1) 33 cout << tree[root].data; 34 else 35 { 36 if(layer > 1) 37 printf("("); 38 DFS(tree[root].lchild,layer+1); 39 cout << tree[root].data; 40 DFS(tree[root].rchild,layer+1); 41 if(layer > 1) 42 printf(")"); 43 } 44 } 45 46 int main() 47 { 48 #ifdef ONLINE_JUDGE 49 #else 50 freopen("Test.txt","r",stdin); 51 #endif 52 53 int n,root; 54 scanf("%d",&n); 55 for(int i=1; i<=n; i++) 56 { 57 cin >> tree[i].data; 58 scanf("%d%d",&tree[i].lchild,&tree[i].rchild); 59 mp[tree[i].lchild]=1; 60 mp[tree[i].rchild]=1; 61 } 62 for(int i=1; i<=n; i++) 63 if(mp[i]==0) 64 root=i; 65 DFS(root,1); 66 67 return 0; 68 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |