二叉数计算器
将表达式二叉树方式存入数组,以递归方式建立表达式之二叉树状结构,再分别输出前序、中序及后序遍历结果,并计算出表达式之结果。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAXSIZE 1024
typedef enum{Char,Double} Flag;
typedef struct
{
double data[MAXSIZE];
int top;
}Stack;
typedef struct binode
{
struct binode *lchild,*rchild;
char data;
double num;
Flag F;
}BiTNode,*BiTree;
Stack *InitStack();
void visit(BiTree T);
void PreOrderTraverse(BiTree T);
void Interordertraversal(BiTree T);
void PostorderTraversal(BiTree T);
BiTree CreatTree(char s[],int i,int j);
double cal(BiTree T)
{
double l,r;
if(T->lchild!=NULL && T->rchild!=NULL)
{
l=cal(T->lchild);
r=cal(T->rchild);
switch (T->data)
{
case '+':
return (l+r);
case '-':
return (l-r);
case '*':
return (l*r);
case '/':
return (l/r);
}
}else
return T->num;
}
Stack *InitStack()
{
Stack *S;
S=(Stack*)malloc(sizeof(Stack));
S->top=-1;
return S;
}
void PreOrderTraverse(BiTree T)
{
if( T )
{
visit(T);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
void Interordertraversal(BiTree T)
{
if( T )
{
Interordertraversal(T->lchild);
visit(T);
Interordertraversal(T->rchild);
}
}
void PostorderTraversal(BiTree T)
{
if( T )
{
PostorderTraversal(T->lchild);
PostorderTraversal(T->rchild);
visit(T);
}
}
void visit(BiTree T)
{
if(T->F==Double)
printf("%.1lf ",T->num);
else
printf("%c ",T->data);
}
BiTree CreatTree(char s[],int i,int j)
{
BiTree p,t;
int k, flag = 0, pos,x=0;
int m=-1,n=-1,num=0;
char str[MAXSIZE];
double sum;
if (i == j)
{
p = (BiTree)malloc(sizeof(BiTNode));
str[x++]=s[i];
str[x]='\0';
sum=atof(str);
p->num = sum;
p->F=Double;
p->lchild = NULL;
p->rchild = NULL;
return p;
}
for (k = j; k >= i; k--)
{
if(s[k]==')')
{
m=k;
do
{
k--;
}while(s[k]!='(');
n=k;
}
if (s[k] == '+' || s[k] == '-')
{
flag = 1;
pos = k;
break;
}
}
if (!flag)
{
for (k = j; k >= i; k--)
{
if(s[k]==')')
{
do
{
k--;
}while(s[k]!='(');
}
if (s[k] == '*' || s[k] == '/')
{
flag = 1;
pos = k;
break;
}
}
}
if(!flag)
{
if(m!=-1)
{
t = (BiTree)malloc(sizeof(BiTNode));
t=CreatTree(s,n+1,m-1);
p=t;
return p;
}
else
{
for(i;i<=j;i++,x++)
{
str[x]=s[i];
}
str[x]='\0';
sum=atof(str);
p = (BiTree)malloc(sizeof(BiTNode));
p->num=sum;
p->F=Double;
p->lchild=NULL;
p->rchild=NULL;
return p;
}
}
if (flag)
{
p = (BiTree)malloc(sizeof(BiTNode));
p->data = s[pos];
p->F=Char;
p->lchild = CreatTree(s, i, pos - 1);
p->rchild = CreatTree(s, pos + 1, j);
return p;
}
else
return NULL;
}
int
main()
{
BiTree p;
Stack *S;
double sum=0;
S=InitStack();
char s[MAXSIZE],s1[MAXSIZE];
printf("请按照中序表示式输入:\n");
gets(s);
p=CreatTree(s,0,strlen(s)-1);
printf("结果:");
sum=cal(p);
printf("%.2lf",sum);
printf("\n先序遍历:");
PreOrderTraverse(p);
printf("\n中序遍历:");
Interordertraversal(p);
printf("\n后序遍历:");
PostorderTraversal(p);
return 0;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/cfda0273fbbd45bab5ebea550e388dd5.png)
|