我不确定我需要做什么来搜索存储在二叉树中的字符串。我已经编写了搜索方法,但我不太明白要传递什么。我需要先搜索字符串,然后再将其添加到树中。如果找到,我只需要增加节点对象内的计数器,而不是添加一个新的。顺便说一下,这棵树是未分类的。
我的问题是如何在添加之前搜索它?
System.out.println("Enter string to be stored");
stringValue = k.nextLine();
if (theString.isEmpty() == true) {
node.add(stringValue, count);
} else {
// I am not sure what to do here
// How do I send the string to my search method?
stringValue.treeSearch();
}
public Node treeSearch(String s, TreeNode root){
if(root.toString().equals(s)){
return root;
}
if(left != null){
left.treeSearch(s, root.left);
if(root.toString().equals(s)){
return root;
}
}
if(right != null){
right.treeSearch(s, root.right);
if(root.toString().equals(s)){
return root;
}
}else{
return null;
}
}
我将搜索方法更新为此。
public Node treeSearch(String s, Node root){
if(root.toString().equals(s)){
return root;
}
if(left != null){
left.treeSearch(s, root.left);
return root;
}
if(right != null){
right.treeSearch(s, root.right);
return root;
}else{
return null;
}
}