• 大小: 6KB
    文件类型: .cpp
    金币: 2
    下载: 1 次
    发布日期: 2021-06-18
  • 语言: C/C++
  • 标签:

资源简介

选择输入前中后缀表达式,建立表达式二叉树,再前序中序后序遍历二叉树,输出三种形式的表达式

资源截图

代码片段和文件信息

//测试数据 前缀表达式 - / * + 1 3 4 5 6
//         中缀表达式 ( 1 + 3 ) * 4 / 5 - 6 #
//         后缀表达式 1 3 + 4 * 5 / 6 - #
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
using namespace std;

class BinaryTreeNode {
public:
string element;
int position;
BinaryTreeNode *leftChild *rightChild;
BinaryTreeNode() {
leftChild = rightChild = NULL;
}
BinaryTreeNode(string elem) {
element = elem;
leftChild = rightChild = NULL;
}
bool isLeaf() {
return leftChild == NULL && rightChild == NULL;
}
};

class BinaryTree {
private:
BinaryTreeNode * mRoot;
int priority(char op) {
switch (op) {
case‘+‘:
case‘-‘:
return 1;
break;
case‘*‘:
case‘/‘:
return 2;
break;
default:
return 3;
}
}
string MtoB() {//中缀表达式转为后缀表达式
char c;
stack s;
int num;
s.push(‘#‘);
ostringstream exp;
for (;;) {
cin >> c;
if (c >= ‘0‘ && c <= ‘9‘) {
cin.putback(c);
cin >> num;
exp << num << ‘ ‘;
}
else if (c == ‘(‘) {
s.push(‘(‘);
}
else if (c == ‘)‘) {
while (s.top() != ‘(‘) {
exp << s.top() << ‘ ‘;
s.pop();
}
if (s.top() == ‘(‘)
s.pop();
}
else if (c == ‘#‘) {
while (s.top() != ‘#‘) {
exp << s.top() << ‘ ‘;
s.pop();
}
break;
}
else {
while (s.top() != ‘#‘ && s.top() != ‘(‘&& priority(s.top()) >= priority(c)) {
exp << s.top() << ‘ ‘;
s.pop();
}
s.push(c);
}
}
exp << ‘#‘;
return exp.str();
}
string PtoB() {//前缀表达式转为后缀表达式
char c[20];
string a b;
scanf(“%s“ c);
if (*c == ‘+‘ || *c == ‘-‘ || *c == ‘*‘ || *c == ‘/‘) {
a = PtoB();
b = PtoB();
return a + ‘ ‘ + b + ‘ ‘ + *c;
}
else return c;
}
void setpostion(BinaryTreeNode* root int pos int k) {
if (root == NULL)return;
root->position = pos;
setpostion(root->leftChild pos - k / 2 k / 2);
setpostion(root->rightChild pos + k / 2 k / 2);
}
public:
BinaryTree() { mRoot = NULL; }
void set(BinaryTreeNode* root) {
mRoot = root;
}
BinaryTreeNode* BulitbyBack(string expression) {
stack s;
BinaryTreeNode* p;
char c;
int n;
istringstream exp(expression);
char i = 0;
for (;;) {
exp >> c;
if (c >= ‘0‘&&c <= ‘9‘) {
exp.putback(c);
exp >> n;
p = new BinaryTreeNode(to_string(n));
s.push(p);
}
else if (c == ‘+‘ || c == ‘-‘ || c == ‘*‘ || c == ‘/‘) {
char op[2] = { c‘\0‘ };
p = new BinaryTreeNode(op);
p->rightChild = s.top();//先弹出的作右子树
s.pop();
p->leftChild = s.top();//后弹出的做左子树
s.pop();
s.push(p);
}
else if (c == ‘#‘) {
break;
}
else assert(0);
}
return s.top();
}

评论

共有 条评论

相关资源