Java 如何进行字符串打印
我不明白为什么当我运行程序时,它不打印字符串。相反,它将打印出数字Java 如何进行字符串打印,java,string,tree,binary-search-tree,compareto,Java,String,Tree,Binary Search Tree,Compareto,我不明白为什么当我运行程序时,它不打印字符串。相反,它将打印出数字 public class Coulter_BST_String { public static void main(String[] args) { String [] input = new String[] { "Matthew", "Ann", "Mary", "Sara", "Kara", "Anthony", "Tom" BinarySearchTree bst = new BinarySearc
public class Coulter_BST_String
{
public static void main(String[] args)
{
String [] input = new String[] { "Matthew", "Ann", "Mary", "Sara", "Kara", "Anthony", "Tom"
BinarySearchTree bst = new BinarySearchTree();
for (int i = 0;i < input.length; i++)
{
bst.insert(input[i]);
}
System.out.println("Preorder Traversal:");
bst.preorderTraversal();
System.out.println( "\nInorder Traversal:");
bst.inorderTraversal();
System.out.println("\nPostorder Traversal:");
bst.postorderTraversal();
}
}
公共类Coulter\u BST\u字符串
{
公共静态void main(字符串[]args)
{
字符串[]输入=新字符串[]{“Matthew”、“Ann”、“Mary”、“Sara”、“Kara”、“Anthony”、“Tom”
BinarySearchTree bst=新的BinarySearchTree();
for(int i=0;i
假设bst.preorderTraversa()
返回一个字符串:
System.out.println("Preorder Traversal: " + bst.preorderTraversal());
您只需要在打印中包含遍历。假设树与您提出的其他问题类似。我不确定它们是否被重新发布或尝试,您有:
public class BinarySearchTree_String
{
private Node root;
public void insert(int key)
{
insert(new Node(key, null, null));
}
public void insert(Node z)
{
Node y = null;
Node x = root;
while (x != null)
{
y = x;
int name = word.compareTo(x.key);
if (name < 0)
{
x = x.getLeftChild();
}
else
{
x = x.getRightChild();
}
}
//make y the parent of z
z.setParent(y);
//checking if there is something inside of y and where to set the vaule that is stroed in y
if (y == null)
{
root = z;
}
//if y is not empty compare again to find which child it must be
else if
(z.getKey().equals(y.getKey()))
{
y.setLeftChild(z);
}
else
{
y.setRightChild(z);
}
}
public void preorderTraversal()
{
preorderTraversal(root);
}
public void preorderTraversal(Node node)
{
if (node != null)
{
//preorder method
System.out.print(node.getKey() + " ");
preorderTraversal(node.getLeftChild());
preorderTraversal(node.getRightChild());
}
}
public void inorderTraversal()
{
inorderTraversal(root);
}
private void inorderTraversal(Node node)
{
if (node != null)
{
//the inorder
inorderTraversal(node.getLeftChild());
System.out.print(node.getKey() + " ");
inorderTraversal(node.getRightChild());
}
}
//to make root show b/c it is hidden
public void postorderTraversal()
{
postorderTraversal(root);
}
private void postorderTraversal(Node node)
{
if (node != null)
{
//post order
postorderTraversal(node.getLeftChild());
postorderTraversal(node.getRightChild());
System.out.print(node.getKey() + " ");
}
}
}
你会看到:
public int getKey()
{
return key;
}
如果键是字符串,则返回整数。应将其更改为:
public String getKey()
{
return key;
}
请提供BinarySearchTree的源代码。没有它,很难理解发生了什么。例如,我不知道是否返回了字符串数组、字符串,或者该方法是否从此返回void。此外,您可能希望使用Java标记它。
public String getKey()
{
return key;
}