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