所以我正在研究一个实现二叉搜索树的学校项目。我必须创建一个将所有节点作为字符串返回的 toString 方法。我能够做到这一点,但我很难弄清楚如何返回所有节点的字符串。
这是我的 void toString 函数。
public void toString(TreeNode node)
{
if (node == null) {
return;
}
if (node.deleted == true) {
System.out.print("*" + node.key + " ");
}
else {
System.out.print(result += node.key + " ");
}
toString(node.leftChild);
toString(node.rightChild);
}
所以我想弄清楚的是如何让它返回树中所有节点的字符串。我尝试了以下但它只返回第一个节点,因为它无法进入递归。
public String toString(TreeNode node)
{
String result="";
if (node == null) {
return "";
}
if (node.deleted == true) {
result += "*" + node.key + " ";
}
else {
result += node.key + " ";
}
toString(node.leftChild);
toString(node.rightChild);
return result;
}
任何帮助将不胜感激。先感谢您。
最佳答案
其实我想我刚刚弄明白了。这就是我所做的,它似乎在正常工作。
public String toString(TreeNode node)
{
String result="";
if (node == null) {
return "";
}
if (node.deleted == true) {
result += "*" + node.key + " ";
}
else {
result += node.key + " ";
}
result += toString(node.leftChild);
result += toString(node.rightChild);
return result;
}
关于Java BNST toString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48920179/