当我在主要方法中调用print方法时,它不会在控制台上打印任何内容。 我想按字母顺序制作一个二叉搜索树。这是为什么?我的插入方法和添加方法是否正确?或者,打印方法有问题吗?为什么我的打印方法无法打印二进制搜索树inorder?
public class Node
{
String value;
Node leftChild;
Node rightChild;
Node(String val,Node left, Node right)
{
value = val;
leftChild = left;
rightChild = right;
}
Node(String val)
{
value = val;
leftChild = null;
rightChild = null;
}
}
public class binarySearchTree
{
Node root;
binarySearchTree()
{
root = null;
}
public Node search(String element)
{
Node current = root;
while (element.compareTo(current.value) != 0)
{
if(current == null)
return null;
else
{
if(element.compareTo(current.value) < 0)
{
current = current.leftChild;
}
else
current = current.rightChild;
}
}
return current;
}
public Node add(String element, Node bstree)
{
if(bstree == null)
{
return new Node(element);
}
else if(element.compareTo(bstree.value) < 0)
{
bstree.leftChild = add(element, bstree.leftChild);
}
else
{
bstree.rightChild = add(element, bstree.rightChild);
}
return bstree;
}
public void insert(String element)
{
add(element,root);
}
public void print(Node bstree)
{
if(bstree != null)
{
print(bstree.leftChild);
System.out.print(bstree.value + " ");
print(bstree.rightChild);
}
}
}
public class testing
{
public static void main(String[] agrs)
{
binarySearchTree tree = new binarySearchTree();
tree.insert("apple");
tree.insert("banana");
tree.insert("kiwi");
tree.print(tree.root);
}
}
是不是我的第一个if语句已经说明树是空的可能性? bstree是根。当bstree为空时,树是空的。 – Rongeegee
如果整个树的根目录为空,那么你必须设置root,以后用它来调用print方法。当前只有if语句检查给定子树的根是否为空,并且只返回一个新节点。 –
“set root”是什么意思? – Rongeegee