如何在这种树上实现中序遍历?我也需要打印运算符(如 3-2-1)。
我有这些类(class):
public class BinaryOperator extends Value {
private Value firstOperand;
private Value secondOperand;
private String operator;
public BinaryOperator(Value firstOperand, Value secondOperand,
String operator) {
this.firstOperand = firstOperand;
this.secondOperand = secondOperand;
this.operator = operator;
}
}
public class Number extends Value {
private Integer value;
public Number(Integer value) {
this.value = value;
}
}
树
Root
/\
/ \
BO Num
/\
/ \
BO OP Num
/\
/ \
Num OP Num
explanation:
- BO: binary operator - consists of two children which may be Num or another BO
- Num: just a number
- OP: operation like +-...
最佳答案
实现这个的规范方法是简单地递归树。
您将首先递归遍历左侧子树,然后打印运算符,然后递归遍历右侧子树。
更高级的实现是使用迭代器和访问者设计模式,但由于这是一道作业题,我认为这不在您的作业范围内。
关于java - 中序树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7951994/