题意:
把后缀表达式转化成二叉树的形式, 再按层次遍历进行输出, 先输出最深层, 逐层向上, 直至最顶层.
思路:
1. 建树: 使用栈, 逐个字符读入, 碰到小写就压栈, 碰到大写, 就弹出栈顶两元素, 分别做为其左,右节点, 并把新生成的节点压栈, 最后栈中剩下的元素就是树的根节点.
2. 遍历: 先获取树的最大深度. 从最深往上逐层遍历, 先递归到达第 N 层, 再输出此层的元素即可.
3. 注意: 这个后缀表达式与正常的表达式是反的, 即正常的 xy- 表示的是 x-y, 这里表示的是 y-x.
要点:
1. "" + char 转 char 为 string.
代码:
# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <cctype>
# include <iterator>
# include <assert.h>
# include <stack>
using namespace std;
// 树节点, 非叶子节点都是操作符, 叶子节点都是运算数
class Node {
public:
Node(char op, Node* left = NULL, Node* right = NULL) {
op_ = op;
left_ = left;
right_ = right;
}
char op_; // 操作符或运算数
Node* left_;
Node* right_;
};
// 对栈执行 op 操作, 即把栈顶两个无素弹出, 并进行 op 操作
// 先弹出来的做为 left, 后弹出来的做为 right
Node* operation(stack<Node*>& stk, char op) {
Node* left = stk.top();
stk.pop();
Node* right = stk.top();
stk.pop();
Node* node = new Node(op, left, right);
stk.push(node);
return node;
}
// 利用栈,创建树, 并返回根节点
// 碰到操作数(小写)就压栈, 碰到运算符就计算
Node* generateTree(const string& line) {
stack<Node*> stk;
Node* root = NULL;
for (int i=0; i<line.size(); i++) {
if (islower(line[i])) {
Node* node = new Node(line[i]);
stk.push(node);
} else {
root = operation(stk, line[i]);
}
}
return root;
}
// 获取树的深度
int getTreeDepth(const Node* root) {
if (root == NULL) return 0;
return 1 + max(getTreeDepth(root->left_), getTreeDepth(root->right_));
}
// 打印树的第 depth 层
// 先递归到第 depth 层, 此时 level == depth , 然后打印
void printTree(const Node* root, int level, int depth) {
if (level == depth) {
cout << root->op_;
return;
}
if (root->left_ != NULL) printTree(root->left_, level+1, depth);
if (root->right_ != NULL) printTree(root->right_, level+1, depth);
}
// 层次遍历进行输出, 使用 队列
void printTree(const Node* root) {
int depth = getTreeDepth(root); // 获取树的最大深度
for (int i=depth; i>0; i--){
printTree(root, 1, i);
}
}
// 释放空间
void freeTree(Node* root) {
if (root == NULL) return;
freeTree(root->left_);
freeTree(root->right_);
delete root;
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("11234_i.txt", "r", stdin);
freopen("uva_o.txt", "w", stdout);
#endif
int numCase;
cin >> numCase;
string line;
while (numCase--) {
cin >> line;
Node* root = generateTree(line);
printTree(root);
freeTree(root);
cout << endl;
}
return 0;
}
环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE