2
如何在这种树上实现InOrder遍历?我也需要打印操作员(如3-2-1)。InOrder树遍历
我有这些类:
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 +-...
我想实际上使用迭代器。是一个很好的方法来运行遍历,将元素放入一个数组然后只读取它们? – user219882
好问题!缺点是你将无法在遍历时删除元素。我宁愿使用链接到每个节点中的父节点,但这样做会导致额外的维护。 –
因为我不必支持'remove'操作,所以我使用最简单的方法来完成它。谢谢... – user219882