Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.
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:
1
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.
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.
Sample Input 1:
1 2 3 4 5 6 7 8 9
8 * 8 7 a -1 -1 * 4 1 + 2 5 b -1 -1 d -1 -1 - -1 6 c -1 -1
n = int(input()) nodes = [Node() for _ in range(n)] for i in range(n): val, left, right = input().split() nodes[i].val = val if left != "-1": nodes[i].left = nodes[int(left) - 1] nodes[i].left.father = nodes[i] if right != "-1": nodes[i].right = nodes[int(right) - 1] nodes[i].right.father = nodes[i]
root = nodes[0] while root.father: root = root.father
ans = [] definorder(i: Node): if i.left or i.right: ans.append("(") if i.left: inorder(i.left) ans.append(i.val) if i.right: inorder(i.right) ans.append(")") else: ans.append(i.val)
inorder(root) ans = ans[1:-1] if len(ans) > 1else ans # 移除最外层括号,要注意只有一个节点的特殊情况。 print("".join(ans))