2011-10-31 180 views
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 +-... 

回答

3

来实现这一点典型的方法就是递归在树。
您将首先递归遍历左侧子树,然后打印操作符,然后递归遍历右侧子树。

更高级的实现将使用迭代器和访问器设计模式,但由于这是一个作业问题,我认为这超出了您的任务范围。

+0

我想实际上使用迭代器。是一个很好的方法来运行遍历,将元素放入一个数组然后只读取它们? – user219882

+0

好问题!缺点是你将无法在遍历时删除元素。我宁愿使用链接到每个节点中的父节点,但这样做会导致额外的维护。 –

+0

因为我不必支持'remove'操作,所以我使用最简单的方法来完成它。谢谢... – user219882