用逗号在 Java 中打印顺序遍历
Printing inorder traversal in Java with commas
我正在尝试在 Java 中打印二叉树的中序遍历实现。我得到以下两个 classes:
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
}
(对于两个 classes 都已经实现了插入方法)
现在我正在尝试为 TreeNode class 实现一个 toString 方法,以实现中序遍历和 return 它作为一个字符串:
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;
}
和Treeclass中的一个方法分别调用对一个Tree根的遍历:
public String toString() {
return "tree[" + root.toString() + "]";
}
现在,我想要的输出应该是这样的:
tree[x,y,z]
我当前的输出如下所示:
tree[x,y,z, ]
我曾尝试将这些值填充到一个数组中,但我正在努力解决这个问题,因为数组不能是可变长度的,除非它是一个我们还不允许使用的 ArrayList。此外,我们不允许使用任何迭代解决方案。我只是不明白如何以没有任何额外 commas/spaces 的方式打印整个内容。任何帮助将不胜感激。
由于您使用的是静态字符串,请检查字符串是否为空并进行相应处理,如下所示:
public String toString() {
if(this.value != 0) {
if (this.hasLeft()) {
this.getLeft().toString();
}
if(s.equals("")){
s += this.getValueString();
}else{
s += ", " + this.getValueString();
}
if (this.hasRight()) {
this.getRight().toString();
}
}
return s;
}
我正在尝试在 Java 中打印二叉树的中序遍历实现。我得到以下两个 classes:
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
}
(对于两个 classes 都已经实现了插入方法)
现在我正在尝试为 TreeNode class 实现一个 toString 方法,以实现中序遍历和 return 它作为一个字符串:
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;
}
和Treeclass中的一个方法分别调用对一个Tree根的遍历:
public String toString() {
return "tree[" + root.toString() + "]";
}
现在,我想要的输出应该是这样的:
tree[x,y,z]
我当前的输出如下所示:
tree[x,y,z, ]
我曾尝试将这些值填充到一个数组中,但我正在努力解决这个问题,因为数组不能是可变长度的,除非它是一个我们还不允许使用的 ArrayList。此外,我们不允许使用任何迭代解决方案。我只是不明白如何以没有任何额外 commas/spaces 的方式打印整个内容。任何帮助将不胜感激。
由于您使用的是静态字符串,请检查字符串是否为空并进行相应处理,如下所示:
public String toString() {
if(this.value != 0) {
if (this.hasLeft()) {
this.getLeft().toString();
}
if(s.equals("")){
s += this.getValueString();
}else{
s += ", " + this.getValueString();
}
if (this.hasRight()) {
this.getRight().toString();
}
}
return s;
}