题意:具体没理解。我知道我这样回答很坑。 根据后缀表达式重建树, 然后输出层次遍历的逆序。
思路: 如何建树?从左往右读入字符, 遇到小写字符建一个结点压入栈中, 遇到一个大写字母建一个结点, 其左右子树便是栈顶的前两个, 构成的新树再压入栈中。 最后只剩一棵树。 然后对这棵树层次遍历(BFS), 输出层次遍历的逆序。
算法复杂度: 缺。
代码:
/*建树*/
#include <cstdio>
#include <cctype>
#include <stack>
#include <queue>
using namespace std;
struct SNode
{
SNode(char ltr = 'a') {
left = NULL;
right = NULL;
letter = ltr;
}
char letter;
SNode *left;
SNode *right;
};
void queueOrder(SNode *);
void removeNode(SNode *&);
int main()
{
int cases;
scanf("%d%*c", &cases);
while (cases--) {
//init
char ch;
stack<SNode *> sta;
while (!sta.empty()) {
sta.pop();
}
while ((ch = getchar()) != '\n') {
if (islower(ch)) {
sta.push(new SNode(ch));
}else if (isupper(ch)) {
SNode *root = new SNode(ch);
root->right = sta.top(); sta.pop();
root->left = sta.top(); sta.pop();
sta.push(root);
}
}
SNode *root = sta.top(); sta.pop();
//output
queueOrder(root);
//free
removeNode(root);
}
return 0;
}
void queueOrder(SNode *star)
{
stack<char> squ;
queue<SNode *> que;
que.push(star);
squ.push(star->letter);
while (!que.empty()) {
SNode *root = que.front();
que.pop();
if (root->left != NULL) {
squ.push(root->left->letter);
que.push(root->left);
}
if (root->right != NULL) {
squ.push(root->right->letter);
que.push(root->right);
}
}
while (!squ.empty()) {
printf("%c", squ.top());
squ.pop();
}
printf("\n");
}
void removeNode(SNode *&root)
{
if (root == NULL) {
return;
}
removeNode(root->left);
removeNode(root->right);
delete root;
root = NULL;
}