#include <stdio.h>
#define PLUS -1
#define MINUS -2
#define UMN -3
struct tree
{
int elem;
tree *left, *right;
};
#include "newfile.h"
int n=0,k=0;
int in(FILE *f, tree **D) //Формирование дерева формулы
{
char ch,t;
fscanf(f,"%c",&ch);
while(!feof(f) && ch != '\n')
{
printf("%c",ch);
if(ch <= '9' && ch >= '0')
{
int x = ch - '0'; //численное значение символа
fscanf(f, "%c", &ch);
while(ch >= '0' && ch <= '9')
{
x = 10*x + ch - '0';
fscanf(f, "%c", &ch);
}
ungetc(ch,f);
(*D)->elem = x;
(*D)->left = (*D)->right = NULL;
return 0;
}
else if(ch == '+')
{
(*D)->elem = PLUS;
(*D)->right = new tree;
(*D)->right->left = (*D)->right->right = NULL;
in(f,&((*D)->right));
}
else if(ch == '-')
{
(*D)->elem = MINUS;
(*D)->right = new tree;
(*D)->right->left = (*D)->right->right = NULL;
in(f,&((*D)->right));
}
else if(ch == '*')
{
(*D)->elem = UMN;
(*D)->right = new tree;
(*D)->right->left = (*D)->right->right = NULL;
in(f,&((*D)->right));
}
else if(ch == '(')
{
k++;
(*D)->left = new tree;
(*D)->left->left = (*D)->left->right = NULL;
in(f,&((*D)->left));
}
else if(ch == ')'){k--; return 0;}
fscanf(f,"%c",&ch);
}
//k++;
return 0;
}
int calc(tree **D) //Высчитывание формулы
{
tree* d = (*D);
if(d->elem >= 0) return d->elem;
else
{
int l = calc(&(d->left));
int r = calc(&(d->right));
switch(d->elem)
{
case PLUS: return l+r; break;
case MINUS: return l-r; break;
case UMN: return l*r; break;
}
}
return 0;
}
void print_tree(tree *d)
{
list Q;
int i=2,j=2,omg;
creatoch(&Q);
if(d!=NULL)
{
intooch(&Q,d,1);
do
{
outoch(&Q,&d,&i);
switch(d->elem)
{
case PLUS: printf("+ "); break;
case MINUS: printf("- "); break;
case UMN: printf("* "); break;
default : printf("%d ",d->elem);
}
if(i!=j) printf("\n");
i++;
if(d->left!=NULL) intooch(&Q,d->left,i);
if(d->right!=NULL) intooch(&Q,d->right,i);
j=i;
}
while(!nulloch(&Q));
}
}
int main()
{ char stroka[15];
int n=1;
tree *D = new tree;
D->left = D->right = NULL;
FILE *f = fopen("input.txt","r");
//fscanf(f,"%s", &stroka);
//printf("%s\n",stroka);
in(f,&D);
int res = calc(&D);
printf("=%d\n",res);
print_tree(D);
}