中序树遍历
如何在这种树上实现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 +-...
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 +-...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的规范方法是简单地在树上递归。
您将首先递归遍历左侧子树,然后打印运算符,然后递归遍历右侧子树。
更高级的实现是使用迭代器和访问者设计模式,但由于这是一个家庭作业问题,我认为这超出了您的作业范围。
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.