首页 > 解决方案 > 编写创建随机表达式的递归方法

问题描述

我应该编写一个递归方法来在表达式树中生成表达式。该方法应该有一个参数来限制表达式树的“高度”。maxHeight 给出了最大允许高度,而不是实际高度。已经创建了常量、变量和二元运算符的节点,但是我在使该方法正常工作时遇到了问题。下面是我创建的方法和树节点之一。我还在学习Java,所以请善待。任何帮助将不胜感激。

static ExpNode randomExpression(int maxHeight) {
        ExpNode e1 = new BinOpNode('+', new VariableNode(), new ConstNode(maxHeight));
        ExpNode e2 = new BinOpNode('*', new ConstNode(maxHeight), new VariableNode());
        ExpNode e3 = new BinOpNode('*', e1, e2);
        ExpNode e4 = new BinOpNode('-', e1, new ConstNode(-3));
        if (maxHeight < 0) {
            return null;
        }
        if (maxHeight == 0) {           
            
            return new BinOpNode('-', e1, e2);
        } 
        if (maxHeight > 0) {            
            maxHeight++;
            return  new BinOpNode('/', e3, e4);
        }
        return randomExpression(maxHeight);
        
    }

static class BinOpNode extends ExpNode {
        char op;  // the operator, which must be '+', '-', '*', or '/'
        ExpNode left, right;  // the expression trees for the left and right operands.
        BinOpNode(char op, ExpNode left, ExpNode right) {
            if (op != '+' && op != '-' && op != '*' && op != '/')
                throw new IllegalArgumentException("'" + op + "' is not a legal operator.");
            this.op = op;
            this.left = left;
            this.right = right;
        }
        double value(double x) {
            double a = left.value(x);  // value of the left operand expression tree
            double b = right.value(x); // value of the right operand expression tree
            switch (op) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            default:  return a / b;
            }
        }
        public String toString() {
            return "(" + left.toString() + op + right.toString() + ")";
        }
    }
      
    
        }

标签: java

解决方案


推荐阅读