InOrder树遍历

时间:2011-10-31 09:43:24

标签: java tree tree-traversal inorder

如何在这种树上实现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 +-... 

1 个答案:

答案 0 :(得分:3)

实现这一目标的规范方法是简单地在树上进行递归 您将首先递归遍历左侧子树,然后打印运算符,然后递归遍历右侧子树。

更高级的实现是使用Iterator和Visitor设计模式,但由于这是一个家庭作业问题,我认为这超出了你的作业范围。