【发布时间】:2021-03-26 02:48:05
【问题描述】:
我正在尝试在 Java 中打印二叉树的中序遍历实现。我有以下两个课程:
public class Tree {
private TreeNode root; // root of the tree, vantage point
}
还有
public class TreeNode {
private TreeNode left; // left successor of current node
private TreeNode right; // right successor of current node
private final int value; // value stored in the current node
}
(两个类都已经实现了插入方法)
现在我正在尝试为 TreeNode 类实现一个 toString 方法,以实现中序遍历并将其作为字符串返回:
static String s = "";
public String toString() {
if(this.value != 0) {
if (this.hasLeft()) {
this.getLeft().toString();
}
s += this.getValueString() + ", ";
if (this.hasRight()) {
this.getRight().toString();
}
}
return s;
}
和Tree类中的一个方法分别调用对树根的遍历:
public String toString() {
return "tree[" + root.toString() + "]";
}
现在,我想要的输出应该是这样的:
tree[x,y,z]
我当前的输出如下所示:
tree[x,y,z, ]
我已尝试将值填充到数组中,但我正在为此苦苦挣扎,因为数组不能是可变长度的,除非它是一个 ArrayList,我们还不允许使用它。此外,我们不允许使用任何迭代解决方案。我只是不明白如何以没有任何额外逗号/空格的方式打印整个内容。任何帮助将不胜感激。
【问题讨论】:
-
这是访问者模式en.wikipedia.org/wiki/Visitor_pattern#Java_example 的一个很好的例子——我现在正在移动,所以不能为你写一个例子,但是搜索“树上的访问者模式”跨度>
标签: java recursion binary-search-tree