使用有序遍历在C ++中评估表达式树

时间:2019-07-03 03:29:24

标签: c++ expression binary-tree

此问题在每日编码问题#50中给出。假设算术表达式作为二叉树给出。每个叶子都是整数,每个内部节点都是“ +”,“-”,“ *”或“ /”之一。

将根赋予这样一棵树,编写一个函数对其求值。

例如,给定以下树:

      *
    /   \
   +     +
  / \   /  \
 3  2  4   5

您应该返回45,因为它是(3 + 2)*(4 + 5)。

我首先想到了好,为什么我不得到这棵树的有序遍历表示的向量并从那里去。我有点卡住了,瞥了一眼在线解决方案。我能够理解并复制它,但对此我并不满意。

到目前为止,我所得到的是向量中这棵树的有序遍历表示形式:[3,+,2,*,4,+,5]。

我想从这里开始对此进行评估,但是我对逻辑有些困惑。

这是我到目前为止无法使用的代码。请注意,binary_tree_calculate2是我正在尝试使用的功能。

// Daily coding problem #50
// This problem was asked by Microsoft.
// Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of
// '+', '−', '∗', or '/'.
// Given the root to such a tree, write a function to evaluate it.
// For example, given the following tree :
//     *
//   /   \
//  +     +
// / \   /  \
// 3  2  4   5
// You should return 45, as it is (3 + 2) * (4 + 5).

#include <cctype>
#include <iostream>
#include <cstring>
#include <utility>
#include <vector>
#include <string>

struct TreeNode
{
    std::string val;
    std::unique_ptr<TreeNode> left = nullptr;
    std::unique_ptr<TreeNode> right = nullptr;

    TreeNode(std::string x, std::unique_ptr<TreeNode> &&p = nullptr, std::unique_ptr<TreeNode> &&q = nullptr) :
        val(x),
        left(std::move(p)),
        right(std::move(q)){}
};


int get_num(std::string c)
{
    return std::stoi(c);
}

auto inordertraversal(std::unique_ptr<TreeNode>& root)
{
    std::vector<std::string> res;
    if (!root)
        return res;

    auto left = inordertraversal(root->left);
    auto right = inordertraversal(root->right);
    res.insert(res.end(), left.begin(), left.end());
    res.push_back(root->val);
    res.insert(res.end(), right.begin(), right.end());
}

int binary_tree_calculate1(std::unique_ptr<TreeNode>& root)
{

    if (!root)
        return 0;

    if (!root->left && !root->right)
        return get_num(root->val);

    int l = binary_tree_calculate1(root->left);
    int r = binary_tree_calculate1(root->right);

    if (root->val == "+")
        return l + r;

    if (root->val == "-")
        return l - r;

    if (root->val == "*")
        return l * r;

    return l/r;
}

int binary_tree_calculate2(std::unique_ptr<TreeNode>& root)
{
    auto tree_node = inordertraversal(root);
    int result = 0;
    for (int i = 0; i < tree_node.size(); ++i)
    {
        int num = get_num(tree_node[i]);
        if (tree_node[i] == "+")
            result += num;
        if (tree_node[i] == "-")
            result -= num;
        if (tree_node[i] == "*")
            result *= num;
        result /= num;
    }
    return result;
}

int main()
{
    std::unique_ptr<TreeNode> root = std::make_unique<TreeNode>("*");
    root->left = std::make_unique<TreeNode>("+");
    root->left->left = std::make_unique<TreeNode>("3");
    root->left->right = std::make_unique<TreeNode>("2");
    root->right = std::make_unique<TreeNode>("+");
    root->right->right = std::make_unique<TreeNode>("5");
    root->right->left = std::make_unique<TreeNode>("4");

    std::cout << binary_tree_calculate1(root) << "\n";
    std::cout << binary_tree_calculate2(root) << "\n";


    std::cin.get();
}

1 个答案:

答案 0 :(得分:1)

一个明显的错误是,在binary_tree_calculate2中,您正在使用result并在末尾用除法破坏它:

for (int i = 0; i < tree_node.size(); ++i)
{
    int num = get_num(tree_node[i]);
    if (tree_node[i] == "+")
        result += num;
    if (tree_node[i] == "-")
        result -= num;
    if (tree_node[i] == "*")
        result *= num;
    result /= num;  // <-- What is this line doing?
}

简而言之,您缺少else条语句:

for (int i = 0; i < tree_node.size(); ++i)
{
    int num = get_num(tree_node[i]);
    if (tree_node[i] == "+")
        result += num;
    else
    if (tree_node[i] == "-")
        result -= num;
    else
    if (tree_node[i] == "*")
        result *= num;
    else 
        result /= num;
}

请注意,假设tree_node[i]将具有数学运算符号,对于除法,num不是0。

binary_tree_calculate1的不同之处在于,return在每次计算后立即完成,因此该函数中不存在错误。