#include#include #include using namespace std; typedef struct node { char data;//当前结点对应的值 struct node* lchild, * rchild;//左子树指针和右子树指针 } *TreeNode, Node; void CreateTree(TreeNode& tree) { char ch; cin >> ch;//键盘输入字符 if (ch == '@')//判断该字符是否为结束标志符 { tree = NULL; } else//不是结束标志符,则运用递归思想创建左子树和右子数 { tree = new Node; tree->data = ch; CreateTree(tree->lchild); CreateTree(tree->rchild); } } void inOrder(TreeNode tree) { if (tree != NULL) { if ((tree->data == '*' || tree->data == '/') && (tree->lchild->data == '+' || tree->lchild->data == '-') && (tree->rchild->data == '-' || tree->rchild->data == '+'))//左右两边都需要加括号 { cout << "("; inOrder(tree->lchild); cout << ")"; cout << tree->data; cout << "("; inOrder(tree->rchild); cout << ")"; } else if ((tree->data == '*' || tree->data == '/') && (tree->lchild->data == '+' || tree->lchild->data == '-' || tree->rchild->data == '-' || tree->rchild->data == '+')) { inOrder(tree->lchild); cout << tree->data; cout << "("; inOrder(tree->rchild); cout << ")"; } else { inOrder(tree->lchild); cout << tree->data; inOrder(tree->rchild); } } } int Calculate(TreeNode tree) { if (tree) { if (tree->data >= '0' && tree->data <= '9') { return tree->data - '0'; } else { if (tree->data == '+') { return Calculate(tree->lchild) + Calculate(tree->rchild); } else if (tree->data == '-') { return Calculate(tree->lchild) - Calculate(tree->rchild); } else if (tree->data == '*') { return Calculate(tree->lchild) * Calculate(tree->rchild); } else if (tree->data == '/') { return Calculate(tree->lchild) / Calculate(tree->rchild); } } } return Calculate(tree); }; int main() { TreeNode T; CreateTree(T); inOrder(T); cout << '='; cout << Calculate(T); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)