Search code examples
javatreetree-traversalinorder

InOrder tree traversal


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 +-... 

Solution

  • 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.