gpt4 book ai didi

java - 为什么我的打印方法无法按顺序打印出二叉搜索树?

转载 作者:太空宇宙 更新时间:2023-11-04 12:01:30 25 4
gpt4 key购买 nike

当我在主方法中调用 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);
}
}

最佳答案

您没有考虑到可能添加到空树的可能性,在这种情况下,您需要专门设置根节点:

public Node add(String element, Node bstree)
{
if (root == null)
{
root = new Node(element);
return root;
}

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;
}

关于java - 为什么我的打印方法无法按顺序打印出二叉搜索树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com