时间限制: 1000 ms 空间限制: 262144 KB 具体限制
题目描述
我们现实生活中通常使用中缀表达式,但在计算机里会用到前缀表达式以及后缀表达式,他们的含义如下:
前缀:先写运算符,接着是第一个操作数,最后是第二个操作数;
后缀:先写第一个操作数,接着写第二个操作数,最后写运算符。
如中缀表达式3 + 4,在前缀表示为+ 3 4,在后缀里表示为3 4 +,而(5 - 4)- 2的前缀为- - 5 4 2,后缀为5 4 - 2 -。
你的任务是输入一个前缀表达式,输出它所对应的后缀表达式。
输入
输入一个前缀表达式,运算符只有“+”和“-”,操作数都是只有1个位数字(0到9),运算符和操作数之间都用一个空格隔开,表达式没有前导空格。每个表达式都是合法的,并且运算符不超过20个。
输出
输出对应的后缀表达式。
输入样例
+ 3 4
输出样例
3 4 +
思路
首先,当我看到这道题的一瞬间,因为数据不大,我直接想到了用根左右建树,再用左右根输出树,话不多说,上代码
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
int num = 1,flag = 0;
struct node{
char data;
node* left;
node* right;
};
node* build(void)
{
node* father = new node;
cin >> father->data;
if(father->data == '+' || father->data == '-'){ //如果是+、-号,说明下面还有数据,就继续建树
father->left = build();
father->right = build();
}
else{
father->left = NULL; //不是的话就停止
father->right = NULL;
}
return father;
}
void Printf(node* father)
{
if(father == NULL) return; //若没有数据就返回
Printf(father->left); //左右根输出
Printf(father->right);
if(flag == 1){
cout << " ";
}
cout << father->data;
flag = 1;
return;
}
int main()
{
int now = 0;
node *head;
head = build();
Printf(head);
return 0;
}
就是这样,希望能对大家的学习有所帮助