Given a syntax tree (binary), you are supposed to output the corresponding postfix expression, with parentheses reflecting the precedences of the operators.node
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.算法
Figure 1express
Figure 2数组
For each case, print in a line the postfix expression, with parentheses reflecting the precedences of the operators.There must be no space between any symbols.post
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)%))+)
现给定一颗语法树,要求输出其后缀表达式。this
后缀表达式实际上就是将a+b的操做符移到最后变为ab+,可是存在特殊状况,由于+和-既能够表明加减法,又能够表明正负号,因此这里得判断+,-是不是和后面的数字绑定在一块儿做为符号位的,判断的方法就是当前的左孩子是否为空,若是为空,那么就说明当前节点的操做符是一个符号位,和右子树的数值是一个总体。不然就是正常的先访问左子树,后访问右子树,最后访问操做符。
综上所述:spa
而后就是对于该数根节点的获取,使用parent数组保存每个节点的根节点,初始为0,只要输入完毕后,其parent值依然为0的,就是根节点。最后进行后序遍历输出便可。3d
#include<cstdio> #include<vector> #include<iostream> using namespace std; struct Node{ string c; int left,right; }node[30]; int parent[30]; void postOrder(int root){ if(root==-1) return; printf("("); if(node[root].left==-1){ // 只有右子树,先输出当前节点,再输出右子树 printf("%s",node[root].c.c_str()); postOrder(node[root].right); printf(")"); }else{ // 左右子树都有,正常后序遍历便可 postOrder(node[root].left); postOrder(node[root].right); printf("%s)",node[root].c.c_str()); } } int main(){ int N; scanf("%d",&N); Node no; for(int i=1;i<=N;++i){ cin>>no.c>>no.left>>no.right; node[i] = no; parent[no.left] = i; parent[no.right] = i; } int root; for(int i=1;i<=N;++i){ if(parent[i]==0){ root = i; break; } } postOrder(root); return 0; }