简体   繁体   English

在二叉树Java中评估表达式

[英]Evaluating an Expression in a Binary Tree Java

I created a Binary Tree of an expression and has the operators (+, -, /, *) as roots and operands (values) as the children left/right. 我创建了一个表达式的二叉树,并以运算符(+,-,/,*)为根,而操作数(值)为左/右子级。 I need to evaluate that expression in the Binary Tree taking the parameters (T, v) where 'T' is the binary tree and 'v' is a node where postorder traversal starts. 我需要使用参数(T,v)在“二叉树”中评估该表达式,其中“ T”是二叉树,“ v”是后遍历开始的节点。

I have searched on how postorder traversal works and all of that which I understand. 我搜索了后遍历的工作方式以及所有我了解的内容。 But I don't know how to implement the code using a node 'v' for the postorder traversal. 但是我不知道如何使用节点'v'进行代码的后遍历。

My method looks like this... 我的方法看起来像这样...

public int evaluateExpression (LinkedBinaryTree<T> tree, Position<T> v) {

}

This should return the operator being used on its operators (children of the root). 这应该返回正在其运算符上使用的运算符(根的子级)。 So, I understand what to do, I am stuck on how to actually do it. 因此,我了解该怎么做,我一直坚持实际操作。 -.- -.-

You don't need to provide the entire tree, and you don't need a separate Position class. 您不需要提供整个树,也不需要单独的Position类。 Every subtree is a tree. 每个子树都是一棵树。 You just need something of this kind: 您只需要这种类型的东西:

public class <T extends Number> ExpressionTree<T> {
    private ExpressionTree<T> left, right;
    private T value;
    private int operator;

    // constructors, getters, setters, etc. elided

    public T evaluateExpression() {
        // Here I am assuming a <T> value field that is set if the node
        // is a literal value rather than an expression subtree with left and right children.
        if (this.value != null)
            return this.value;
        // Evaluate the subtree
        switch (this.operator) {
        case '+':
            return left.evaluateExpression()+right.evaluateExpression();
        // etc for the other operators
        }
    }

You should not use the LinkedBinaryTree class mentioned in comments below. 您不应使用下面的注释中提到的LinkedBinaryTree类。 It is not designed for this purpose in any way, and appears to me to be needlessly complex even for its own purpose. 它不是为任何目的而设计的,在我看来,即使出于其自身的目的,它也不必要地复杂。

Normally, in the real world, you would do this as EJP suggests. 通常,在现实世界中,您会按照EJP的建议进行操作。

That said, a postorder iterator will give you the the values and the operators stored in the tree in the right order to do basically this: 也就是说,后置迭代器将按正确的顺序为您提供存储在树中的值和运算符,基本上可以做到这一点:

  • If the element is a number, push it on a number stack 如果元素是数字,则将其压入数字堆栈
  • If the element is an operation, pop two elements from the number stack, process them according to the operation and push the result 如果该元素是一个运算,请从数字堆栈中弹出两个元素,然后根据该运算对其进行处理并推送结果

After the traversal, return the only element on the stack 遍历后,返回堆栈上的唯一元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM