中序树遍历

发布于 2024-12-13 03:59:18 字数 897 浏览 0 评论 0原文

如何在这种树上实现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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

有木有妳兜一样 2024-12-20 03:59:18

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文