java - 编写创建随机表达式的递归方法
问题描述
我应该编写一个递归方法来在表达式树中生成表达式。该方法应该有一个参数来限制表达式树的“高度”。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() + ")";
}
}
}
解决方案
推荐阅读
- c# - 如何在控制台中查看列表的内容?
- node.js - 如何通过url在节点js中呈现日志/文本文件?
- c++ - C++ unique_ptr() 用法
- javascript - React 内联样式不会影响我的自定义组件
- maven - Maven(-exec-plugin) 解析 *(星号)符号
- c# - 无法解析范围服务
- android - 等待 AsyncTask postExecute 继续
- python - Python & BeautifulSoup 4/Selenium - 无法从 kicksusa.com 获取数据?
- generics - 泛型 - 约束到相同的子类型
- android - 如何将转义的 JSON 行传输到 bean 列表