二叉树的表达式计算(10以内运算)雏形
---恢复内容开始---
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;
typedef struct tree{
char data;
tree *lchild;
tree *rchild;
}Bitree,*pBitree;
stack<char>sta1;
stack<char>sta2;
void creat_tree(pBitree &root)
{
char ch='#';
if (!sta1.empty())
{
ch = sta1.top();
sta1.pop();
}
root = new Bitree;
root->data = ch;
if (ch != '+' && ch != '-' && ch != '*' && ch != '/')
{
root->rchild = NULL;
root->lchild = NULL;
return;
}
else
{
creat_tree(root->rchild);
creat_tree(root->lchild);
}
}
void preorder(pBitree root)
{
if (root!=NULL)
{
printf("%c", root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
void postorder(pBitree T) //后序遍历 递归
{
if (T)
{
postorder(T->lchild);
postorder(T->rchild);
printf("%c", T->data);
}
}
void inorder(pBitree T) //中序遍历 递归
{
if (T)
{
inorder(T->lchild);
printf("%c", T->data);
inorder(T->rchild);
}
}
int judge(char t)
{
char ch='#';
ch = sta2.top();
switch (t)
{
case '+':
case '-':
{
if (ch == '+' || ch == '-' || ch =='*' || ch == '/')
return 1;
else
return 0;
break;
}
case'*':
case'/':
{
if (ch == '*' || ch == '/')
return 1;
else
return 0;
}
}
}
void turn_postorder(char *str) //变为后缀表达式
{
char ch='#';
for (int i = 0; i < strlen(str); i++)
{
if ('0' <= str[i] && str[i] <= '9')
{
sta1.push(str[i]);
}
else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/')
{
while (!sta2.empty() && judge(str[i]))
{
ch = sta2.top();
sta1.push(ch);
sta2.pop();
}
sta2.push(str[i]);
}
else if (str[i] == '(')
{
sta2.push(str[i]);
}
else if (str[i] == ')')
{
while ((ch = sta2.top())!= '(')
{
sta1.push(ch);
sta2.pop();
}
sta2.pop();
}
}
while (!sta2.empty())
{
ch = sta2.top();
sta2.pop();
sta1.push(ch);
}
/*while (!sta1.empty())
{
ch = sta1.top();
printf("%c", ch);
sta1.pop();
}*/
}
char result(pBitree root)
{
char num1, num2;
int n1, n2;
switch (root->data)
{
case '+':
num1 = result(root->lchild);n1 = num1 - '0';
num2 = result(root->rchild); n2 = num2 - '0';
root->data = n1+n2+'0';
break;
case'-':
num1 = result(root->lchild); n1 = num1 - '0';
num2 = result(root->rchild); n2 = num2 - '0';
root->data = n1 - n2 + '0';
break;
case '*':
num1 = result(root->lchild); n1 = num1 - '0';
num2 = result(root->rchild); n2 = num2 - '0';
root->data = n1*n2 + '0';
break;
case '/':
num1 = result(root->lchild); n1 = num1 - '0';
num2 = result(root->rchild); n2 = num2 - '0';
root->data = n1 / n2 + '0';
break;
}
return root->data;
}
int main()
{
char str[50], res;
int r;
pBitree root=NULL;
while (1){
printf("请输入表达式:");
scanf("%s", &str);
turn_postorder(str);
creat_tree(root);
preorder(root);
printf("先序遍历\n");
inorder(root);
printf("中序遍历\n");
postorder(root);
printf("后序遍历\n");
result(root);
printf("结果:");
res=result(root);
r = res - '0';
printf("%d", r);
}
system("pause");
return 0;
}
//(5-7)*(9-7)-1
//(5-1)-1
参考http://www.cqvip.com/read/read.aspx?id=42407179#
---恢复内容结束---