C++用树实现汇总缀表达式求值

C++用树实现汇总缀表达式求值,第1张

C++用树实现汇总缀表达式求值
#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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5520994.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存