Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.
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:
data left_child right_childwhere 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.
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.
题意:给出一个二叉树,输出他的中缀表达式,并且加上括号表示他的优先级 思路:在输入数据的时候把左子树和右子树的数存入到have数组中,与结点的编号比较一下,如果没有在have数组中出现的就是根节点。然后dfs拼接中缀表达式,dfs递归拼接“(” + 左子树 + 根 + 右子树 + “)”递归有四种情况有效的只有三种:
左子树和右子树都空:返回“(” + 根 + “)”左子树为空,右子树不空:返回“(” + 左子树 + 根 + “)”左子树不为空,右子树为空:不成立左右子树都不空:返回“(” + 左子树 + 根 + 右子树 + “)” #include<iostream> #include<cstdio> #include<stack> #include<queue> #include<vector> #include<algorithm> #include<cstring> #include<string> #include<cmath> #include<set> #include<map> #include<cctype> #include<cstdlib> #include<ctime> using namespace std; struct node { string data; int l,r; } a[30]; string dfs(int root) { if(a[root].l == -1 && a[root].r == -1) return a[root].data; if(a[root].l == -1 && a[root].r != -1) return "(" + a[root].data + dfs(a[root].r) + ")"; if(a[root].l != -1 && a[root].r != -1) return "(" + dfs(a[root].l) + a[root].data + dfs(a[root].r) + ")"; } int main() { int n,root; scanf("%d",&n); int have[30] = {0}; for(int i = 1;i <= n;i++) { cin >> a[i].data >> a[i].l >> a[i].r; if(a[i].l != -1) have[a[i].l] = 1; if(a[i].r != -1) have[a[i].r] = 1; } for(int i = 1;i <= n;i++) { if(have[i] == 0) { root = i; break; } } string ans = dfs(root); if(ans[0] == '(') ans = ans.substr(1,ans.size() - 2); cout << ans << endl; return 0; }