3

この種のツリーに 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 +-... 
4

1 に答える 1

3

これを実装する標準的な方法は、単純にツリーを再帰することです。
最初に左側のサブツリーを再帰的にトラバースし、次に演算子を出力してから、右側のサブツリーを再帰的にトラバースします。

より高度な実装は、Iterator および Visitor デザイン パターンを使用することですが、これは宿題の質問であるため、課題の範囲外であると思います。

于 2011-10-31T09:48:26.247 に答える