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.
Figure 1Figure 2For 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数组判断该结点是否有父结点,这样在输入完成时就能知道哪一个结点是根结点了。再通过dfs遍历,返回string类型的表达式。注意需要判断是否需要去除括号,一般情况下是需要去除最外层的括号的,但是如果这个数只有一个结点,那就不会出现括号,不用去除。如果不判断直接把括号去除了,会有一个测试点过不了。
