SSLZYC 前缀转后缀

题目大意:
输入一个前缀表达式,输出它所对应的后缀表达式。
前缀:先写运算符,接着是第一个操作数,最后是第二个操作数;
后缀:先写第一个操作数,接着写第二个操作数,最后写运算符。


思路:
emm…
想了好一会 然而还是不会 ,发现这道题有两处细节:
(1)前缀和后缀的数字顺序完全一样
(2)前缀和后缀的符号顺序完全相反
然而这道题我最后还是用二叉树做的……
不难发现,前缀的顺序是“根左右”,后缀的顺序是“左右根”,那利用这条重要的第三处细节,我们就可以只用5行主代码完成这道题。


代码:

#include <cstdio>
#include <iostream>
using namespace std;

char c[101],ch;

void read(int x)  //读入
{
    ch=getchar();
    if (ch==' ') ch=getchar();  //读入字符
    if (ch==10) return;  //换行符特判
    if (ch>='0'&&ch<='9')   //如果是数字
    {
        c[x]=ch;
        return;  //返回
    }
    if (ch=='+'||ch=='-')  //如果是字符
    {    
        c[x]=ch;
        read(x*2);  //找子节点
        read(x*2+1);  //还是找子节点
    }
}

void write(int x)  //输出
{
    if (c[x]=='+'||c[x]=='-')  //如果是字符
    {
        write(x*2);  //先输出数字
        write(x*2+1);  //还是先输出数字
    }
    if (c[x]!=' ') printf("%c ",c[x]);  //输出字符
}

int main()  //仅有的5行代码
{
    freopen("j4.in","r",stdin);
    freopen("j4.out","w",stdout);  //文件输入输出2行
    read(1);  //读入1行
    write(1);  //输出1行
    return 0;  //结束程序1行
}
原文地址:https://www.cnblogs.com/hello-tomorrow/p/9313111.html