3

How can I implement InOrder traversal on this kind of tree? I need to print the operators too (like 3-2-1).

I have these classes:

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
  • 15,274
  • 23
  • 93
  • 138

1 Answers1

3

The canonical way to implement this is to simply recurse over the tree.
You would first recursively traverse the left-hand subtree, then print the operator, then recursively traverse the right-hand subtree.

A more advanced implementation would be to use the Iterator and Visitor design patterns, but since this is a homework question, I assume that is outside the scope of your assignment.

  • I would like to use iterator actually. Is a good way to run the traversal, put the elements into an array and then just read them? – user219882 Oct 31 '11 at 10:18
  • Good question! The drawback is that you would be unable to delete the elements while traversing. I would prefer using links to the parent node in each node, but doing so causes extra maintenance. – S.L. Barth is on codidact.com Oct 31 '11 at 11:17
  • Since I don't have to support the `remove` operation, I used the most simple way to do it. Thank you... – user219882 Oct 31 '11 at 11:26