我如何用to String方法打印出我的二叉树



我对我的二叉树代码有一个问题。首先,我有3个变量:

  • int node为编号

  • 左树的boolean lhs = null

  • 右树boolean rhs = null

我想打印出我的二叉树,但是我的代码不能正常工作:

public String toString () {
if (lhs == null) {
} else if (rhs == null) {
return "Baum ist leer";
}
if (lhs != null) {
}
else if (rhs != null){
return rhs.toString();
}
}

这是我的代码,但是我在控制台得到的唯一输出是:

Baum ist leer

…我不知道为什么,因为我的树不是空的。我找不到我的错误。

这是插入到树中的代码:

public void add(int insert) {   
if (node > insert) {
if (lhs == null) {
lhs = new Tree(insert);
} else {
lhs.add(insert);
}
} else if (node < insert) {
if (rhs == null) {
rhs = new Tree(insert);
} else {
rhs.add(insert);
}
}
}

您的第一个条件不正确。这段代码的意思是:

if (lhs == null) {
//Code here will run if lhs equals to null, regardless the other variables values.
} else if (rhs == null) {
//Code here will run if lhs isn't null, but rhs equals null.
return "Baum ist leer";
}

根据你的返回,我认为你试着让你的else if运行,如果它们都是空的,这段代码做:

if(lhs == null){
if(rhs == null){
//Code here will run only if both lhs and rhs are null.
return "Baum ist leer";
}
}

或者,更简洁的代码:

if(lhs == null && rhs == null){
//Code here will run only if both lhs and rhs are null.
return "Baum ist leer";
}

如果我误解了你的目的,请在下面评论。

你只能得到" Baum " list ";作为返回值,是因为您的函数永远不会返回任何其他值。它唯一一次返回字面值字符串是在这里:

return "Baum ist leer";

它唯一的返回值是:

return rhs.toString();

. .这是一个递归调用,只能导致另一个递归调用或一些不进行递归调用的return。由于您只有一个这样的不进行递归调用的return,因此除了"Baum ist leer"之外,您不可能获得任何其他字符串。

其次,函数要保证总是返回一个字符串,所以应该没有空的if块。

最后,toString方法中没有代码读取节点的数据,因此该函数不可能返回包含节点数据的字符串。

旁注:您将树节点的数据命名为node,这令人困惑。最常见的是将对象称为节点,并将其数据称为datavalue,或类似的东西。但是把它命名为node是令人困惑的。

下面是toString的实现,它返回一个多行字符串,其中每行表示一个节点,节点号的缩进表示它在树结构中的位置。根将没有缩进,因此出现在最左边,而树的最深的叶子将出现在最右边。

// Helper
private String indentedString(Tree tree, String indent) {
if (tree == null) {
return "";
}
return indentedString(tree.rhs, indent + "  ") 
+ indent + tree.node + "n"
+ indentedString(tree.lhs, indent + "  ");
}

public String toString () {
return indentedString(this, "");
}

最新更新