【问题标题】:Calculator Algorithm - Using Iteration instead of Recursion on Binary Search Tree计算器算法 - 在二叉搜索树上使用迭代而不是递归
【发布时间】:2015-05-10 15:58:49
【问题描述】:

我已经看到了有关如何遍历二叉树并找到所有节点之和的方法,但我正在评估计算器的表达式输入。节点根据操作顺序以适当的顺序排列,节点为operatorsoperands。我认为recursion 比迭代慢,所以我想弄清楚如何遍历二叉树并找到没有recursion 输入的表达式的结果。

树的一个例​​子:

      +
  *       /
3   4   4   2

目前为止我使用的递归方法(我使用了一个枚举作为运算符):

public static float evaluate(BETNode root)
{
    if (root == null)
    {
        throw new IllegalArgumentException("Error: Root is null!");
    }

    if (root.getType() == BETNodeType.OPERAND)
    {
        return root.getOperand();
    }

    float leftValue = evaluate(root.getLeft());
    float rightValue = evaluate(root.getRight());

    switch (root.getOperator())
    {
        case '+':
            return leftValue + rightValue;

        case '-':
            return leftValue - rightValue;

        case '*':
            return leftValue * rightValue;

        case '/':
            return leftValue/rightValue;
    }

    throw new IllegalArgumentException("Error.");
}

【问题讨论】:

    标签: java algorithm recursion binary-tree


    【解决方案1】:

    正如我在上面的评论中提到的,如果您执行iterative post-order traversal,您将按顺序获得节点:

    3, 4, *, 4, 2, /, +.

    因此,您只需要一个堆栈来计算表达式。

    Push 3
    Push 4
    Push (pop() * pop())
    
    Push 4
    Push 2
    Push (pop() / pop())
    Push (pop() + pop())
    //Result
    

    同样有趣的是Shunting Yard Algorithm,它根据中缀表达式进行评估。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 2014-05-10
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2023-03-05
      相关资源
      最近更新 更多