如何在这种树上实现InOrder遍历?我还需要打印运算符(如3-2-1)。
我有以下几个类:
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;
}
}Tree
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 +-... 发布于 2011-10-31 17:48:26
实现这一点的规范方法是简单地在树上递归。
首先递归遍历左侧的子树,然后打印运算符,然后递归遍历右侧的子树。
更高级的实现是使用Iterator和Visitor设计模式,但由于这是一个家庭作业问题,我认为这超出了您的任务范围。
https://stackoverflow.com/questions/7951994
复制相似问题