1130 Infix Expression (25 分)(找規律、中序遍歷)html
我是先在CSDN上面發表的這篇文章https://blog.csdn.net/weixin_44385565/article/details/89035813node
Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.ios
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:express
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.this
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.spa
8 * 8 7 a -1 -1 * 4 1 + 2 5 b -1 -1 d -1 -1 - -1 6 c -1 -1
(a+b)*(c*(-d))
8 2.35 -1 -1 * 6 1 - -1 4 % 7 8 + 2 3 a -1 -1 str -1 -1 871 -1 -1
(a*2.35)+(-(str%871))
題目大意:將語法樹輸出爲中綴表達式。.net
思路:字符就是中序遍歷輸出的順序,須要注意括號的位置,觀察兩個樣例能夠總結出規律 :除了根節點,每個運算符都有一對括號,且該運算符對應的左括號在該運算符的左子樹以前輸出(找到運算符後在進入下層遞歸以前輸出),右括號在該運算符的右子樹以後輸出(找到運算符後等待右子樹遞歸輸出完再輸出);所以以非根節點的運算符的位置爲判斷依據,即非根節點的非葉子節點。。。code
妙啊!一下就將二叉樹的前中後遍歷所有考察到了而且將考察的內容隱藏在括號出現的規律裏面~~orm
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 using namespace std; 5 struct node { 6 string data; 7 int left, right; 8 }; 9 int root; 10 void inorder(vector<node> &v, int index); 11 int main() 12 { 13 int N; 14 scanf("%d", &N); 15 vector<node> v(N + 1); 16 vector<int> flag(N + 1, 0); 17 for (int i = 1; i <= N; i++) { 18 string tmp; 19 int left, right; 20 cin >> tmp; 21 scanf("%d%d", &left, &right); 22 v[i] = { tmp,left,right }; 23 if (left != -1) flag[left] = 1; 24 if (right != -1) flag[right] = 1; 25 } 26 for (int i = 1; i <= N; i++)//尋找根節點 27 if (flag[i] != 1) { 28 root = i; 29 break; 30 } 31 inorder(v, root); 32 return 0; 33 } 34 void inorder(vector<node> &v, int index) 35 { 36 if (index != -1) { 37 if (index != root && (v[index].left != -1 || v[index].right != -1)) 38 printf("("); 39 inorder(v, v[index].left); 40 cout<<v[index].data; 41 inorder(v, v[index].right); 42 if (index != root && (v[index].left != -1 || v[index].right != -1)) 43 printf(")"); 44 } 45 }
原文出處:https://www.cnblogs.com/yinhao-ing/p/10657226.htmlhtm