【发布时间】:2016-11-29 01:18:40
【问题描述】:
当我在 main 方法中调用 print 方法时,它不会在控制台上打印任何内容。 我正在尝试按字母顺序制作二叉搜索树。为什么会这样?我的插入方法和添加方法是否正确?或者,是不是打印方式有问题?
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);
}
}
【问题讨论】:
标签: java linked-list tree binary-search-tree