后缀表达式转表达式树
- 定义一个树结点的结构体。
- 开一个栈存储结点
- 逐个扫描后缀表达式:
- 如果是数字,直接开一个结点放入栈中。
- 如果是操作符:
从栈中弹出两个结点,作为一个新开结点的儿子。最后将新开的结点放回栈中。
- 结束后,栈顶就是表达式树的根结点。
// 这里数字只有一位,如果出现 >10 的数字话还要加一个读数字的处理
struct TreeNode {
char val; // 这里可以修改类型
TreeNode *lson, *rson; // 左右儿子
TreeNode(char _val, TreeNode *_lson = nullptr, TreeNode *_rson = nullptr) :
val(_val), lson(_lson), rson(_rson) {}
};
TreeNode *build(const std::string &str) { // 返回表达式树的根节点
std::vector<TreeNode *> nodes;
for (auto ch : str) {
if (isdigit(ch)) { // 数字
nodes.push_back(new TreeNode(ch));
} else { // 操作符
auto r = nodes.back(); nodes.pop_back();
auto l = nodes.back(); nodes.pop_back();
TreeNode *tmp = new TreeNode(ch);
tmp->lson = l, tmp->rson = r;
nodes.push_back(tmp);
}
}
return nodes.back();
}