#include <bits/stdc++.h> using namespace std; typedef string ElemType; typedef struct BitNode { ElemType data; struct BitNode lchild,rchild; } BitNode,BiTree; //char sc[10]= {"+-/"}; void CreateBiTree(BiTree &t) { string ch; cin >> ch; if(ch[0] == '#') t = NULL; else { t = new BitNode; t->data = ch; CreateBiTree(t->lchild); CreateBiTree(t->rchild); } } int InOrderTraverse(BiTree t) { string op = t->data; int a,b; if(op[0]<'0' || op[0]>'9') { cout << '('; a = InOrderTraverse(t->lchild); cout << t->data ; b = InOrderTraverse(t->rchild); cout << ')'; if(op == "+") return a+b; else if(op == "-") return a-b; else if(op == "") return ab; else return a/b; } else { //InOrderTraverse(t->lchild); cout << t->data; //InOrderTraverse(t->rchild); int num=0; for(int i=0;i<op.size();i++){ num = num*10 + op[i]-'0'; } return num; } } int main() { BiTree tree = new BitNode; string ch; int sum; while(cin >> ch) { tree->data = ch; CreateBiTree(tree->lchild); CreateBiTree(tree->rchild); sum = InOrderTraverse(tree); printf("=%d\n",sum); } return 0; }换成c语言形式
时间: 2024-03-14 10:46:04 浏览: 155
以下是将您提供的 C++ 代码转换为 C 语言的等价代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct BitNode {
ElemType data;
struct BitNode *lchild, *rchild;
} BitNode, *BiTree;
void CreateBiTree(BiTree *t) {
char ch[10];
scanf("%s", ch);
if (ch[0] == '#') {
*t = NULL;
} else {
*t = (BitNode *)malloc(sizeof(BitNode));
(*t)->data = ch[0];
CreateBiTree(&((*t)->lchild));
CreateBiTree(&((*t)->rchild));
}
}
int InOrderTraverse(BiTree t) {
char op = t->data;
int a, b;
if (op < '0' || op > '9') {
printf("(");
a = InOrderTraverse(t->lchild);
printf("%c", op);
b = InOrderTraverse(t->rchild);
printf(")");
if (op == '+')
return a + b;
else if (op == '-')
return a - b;
else if (op == '*')
return a * b;
else
return a / b;
} else {
int num = 0;
for (int i = 0; i < strlen(&(t->data)); i++) {
num = num * 10 + t->data[i] - '0';
}
return num;
}
}
int main() {
BiTree tree = NULL;
char ch[10];
int sum;
while (scanf("%s", ch) != EOF) {
tree = (BitNode *)malloc(sizeof(BitNode));
tree->data = ch[0];
CreateBiTree(&(tree->lchild));
CreateBiTree(&(tree->rchild));
sum = InOrderTraverse(tree);
printf("=%d\n", sum);
}
return 0;
}
```
阅读全文