Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.node
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:ios
data left_child right_child
where data
is a string of no more than 10 characters, left_child
and right_child
are the indices of this node's left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented by −1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.express
Figure 1 | Figure 2 |
Output Specification:
For each case, print in a line the infix expression, with parentheses reflecting the precedences of the operators. Note that there must be no extra parentheses for the final expression, as is shown by the samples. There must be no space between any symbols.ide
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))
1 #include <stdio.h> 2 #include <algorithm> 3 #include <iostream> 4 #include <map> 5 #include <string> 6 #include <vector> 7 #include <set> 8 #include <cctype> 9 using namespace std; 10 const int maxn=30; 11 int n,m,k; 12 set<int> adj[maxn]; 13 struct node{ 14 string data; 15 int left; 16 int right; 17 }; 18 node tree[maxn]; 19 int isroot[maxn]={0}; 20 int troot; 21 void midorder(int root){ 22 if(root==-1)return; 23 if(root!=troot && !(tree[root].left==-1 && tree[root].right==-1))printf("("); 24 midorder(tree[root].left); 25 printf("%s",tree[root].data.c_str()); 26 midorder(tree[root].right); 27 if(root!=troot && !(tree[root].left==-1 && tree[root].right==-1))printf(")"); 28 } 29 int main(){ 30 scanf("%d",&n); 31 for(int i=1;i<=n;i++){ 32 string s; 33 int left,right; 34 cin>>s>>left>>right; 35 tree[i].data=s; 36 tree[i].left=left; 37 tree[i].right=right; 38 if(left!=-1)isroot[left]=1; 39 if(right!=-1)isroot[right]=1; 40 } 41 for(int i=1;i<=n;i++){ 42 if(isroot[i]!=1){ 43 troot=i; 44 break; 45 } 46 } 47 midorder(troot); 48 }
注意點:根據給定輸入建一棵樹,再輸出中綴表達式,難點在於括號的處理。看了半天的思路是這樣的:葉子節點若是是左子樹就在這個葉子節點左子樹上再加一個括號節點,是右子樹葉子節點就在右子樹上加個括號節點,中間的節點若是沒有左子樹也加個括號節點,最後看括號數量對不對在結尾補括號。看上去這思路還不錯,但徹底不知道該怎麼寫代碼實現它,只好看大佬思路,發現思路大致上是對的,就是想實現的方式有問題。this
在左葉節點的左邊加括號,其實就是在中序遍歷時判斷這個節點是否是葉子節點和根節點,不是就在先後輸出括號。腦子沒轉過來,難。spa