ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

1628. Design an Expression Tree With Evaluate Function 用一串运算符来构建二叉树

2021-08-29 09:03:04  阅读:357  来源: 互联网

标签:Function Node return evaluate tree 运算符 二叉树 expression public


Given the postfix tokens of an arithmetic expression, build and return the binary expression tree that represents this expression.

Postfix notation is a notation for writing arithmetic expressions in which the operands (numbers) appear before their operators. For example, the postfix tokens of the expression 4*(5-(7+2)) are represented in the array postfix = ["4","5","7","2","+","-","*"].

The class Node is an interface you should use to implement the binary expression tree. The returned tree will be tested using the evaluate function, which is supposed to evaluate the tree's value. You should not remove the Node class; however, you can modify it as you wish, and you can define other classes to implement it if needed.

binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (numbers), and internal nodes (nodes with two children) correspond to the operators '+' (addition), '-' (subtraction), '*' (multiplication), and '/' (division).

It's guaranteed that no subtree will yield a value that exceeds 109 in absolute value, and all the operations are valid (i.e., no division by zero).

Follow up: Could you design the expression tree such that it is more modular? For example, is your design able to support additional operators without making changes to your existing evaluate implementation?

 

Example 1:

Input: s = ["3","4","+","2","*","7","/"]
Output: 2
Explanation: this expression evaluates to the above binary tree with expression ((3+4)*2)/7) = 14/7 = 2.

Example 2:

Input: s = ["4","5","2","7","+","-","*"]
Output: -16
Explanation: this expression evaluates to the above binary tree with expression 4*(5-(2+7)) = 4*(-4) = -16.

Example 3:

Input: s = ["4","2","+","3","5","1","-","*","+"]
Output: 18

Example 4:

Input: s = ["100","200","+","2","/","5","*","7","+"]
Output: 757

用stack,加一个节点同时就pop一个出来。这个我挺没想到的。

参考:https://leetcode.com/problems/design-an-expression-tree-with-evaluate-function/discuss/1209901/Java-Factory-method-pattern

abstract class Node {
    public abstract int evaluate();
    
    public static Node from(String value) {
        switch(value) {
            case "+":
                return new AdditionNode();
            case "-":
                return new SubtractionNode();
            case "*":
                return new MultiplicationNode();
            case "/":
                return new DivisionNode();
            default:
                return new NumericalNode(value);
        }
    }
};

abstract class OperatorNode extends Node {
    protected Node left;
    protected Node right;
    
    public void setLeft(Node left) {
        this.left = left;
    }
    
    public void setRight(Node right) {
        this.right = right;
    }
}

class AdditionNode extends OperatorNode {
    public int evaluate() {
        return left.evaluate() + right.evaluate();
    }
}

class SubtractionNode extends OperatorNode {
    public int evaluate() {
        return left.evaluate() - right.evaluate();
    }
}

class MultiplicationNode extends OperatorNode {
    public int evaluate() {
        return left.evaluate() * right.evaluate();
    }
}

class DivisionNode extends OperatorNode {
    public int evaluate() {
        return left.evaluate() / right.evaluate();
    }
}

class NumericalNode extends Node {
    private String value;
    
    public NumericalNode(String v) {
        value = v;
    }
    
    public int evaluate() {
        return Integer.valueOf(value);
    }
}

class TreeBuilder {
    Node buildTree(String[] postfix) {
        Stack<Node> st = new Stack<>();
        
        for (String s : postfix) {
            Node n = Node.from(s);
            if (n instanceof NumericalNode) {
                st.push(n);
            } else if (n instanceof OperatorNode) {
                OperatorNode op = (OperatorNode) n;
                op.setRight(st.pop());
                op.setLeft(st.pop());
                st.push(op);
            } else {
                throw new IllegalStateException("node should be instance of NumericalNode or OperatorNode");
            }
        }
        
        return st.pop();
    }
};

 

 
 

标签:Function,Node,return,evaluate,tree,运算符,二叉树,expression,public
来源: https://www.cnblogs.com/immiao0319/p/15201856.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有