Java 检查BinarySearchTree中的重复值
我一直在寻找我的BinarySearchTree,以防Java 检查BinarySearchTree中的重复值,java,Java,我一直在寻找我的BinarySearchTree,以防文件f有重复的值,而不是在找到文件f的第一个实例后就结束。我需要返回文件f的所有实例 现在,这是我查找文件的代码 public File locateHelper(File f, Node<File> node) { if (node == null) { return null; } int result = f.compareTo(node.data); if (result
文件f
有重复的值,而不是在找到文件f
的第一个实例后就结束。我需要返回文件f
的所有实例
现在,这是我查找文件的代码
public File locateHelper(File f, Node<File> node) {
if (node == null) {
return null;
}
int result = f.compareTo(node.data);
if (result == 0) {
return f;
}
if (result < 0) {
return locateHelper(f, node.leftChild);
}
return locateHelper(f, node.rightChild);
}
public File locateHelper(文件f,节点){
if(node==null){
返回null;
}
int result=f.compareTo(node.data);
如果(结果==0){
返回f;
}
如果(结果<0){
返回locateHelper(f,node.leftChild);
}
返回locateHelper(f,node.rightChild);
}
我一直试图切换此选项以返回一个ArrayList
而不是单个文件,但我一直遇到NullPointerException
问题
你们会怎么做呢?我会用这样的方法来解决这个问题:
public ArrayList<File> collectTree( Node<File> root )
{
List<File> files = new ArrayList<>();
collectTree( root, files );
return files;
}
private void collectTree( Node<File> node, ArrayList<File> files )
{
if( node == null )
return;
collectTree( node.leftChild, files );
files.add( node.data );
collectTree( node.rightChild, files );
}
您计划通过什么搜索文件,以及如何处理多个匹配的情况?你想要所有的文件还是只想要第一个?我想要那些与文件f
相等的文件。好的,我明白了。所以,答案是,“使用访客模式,卢克!”是的,不幸的是,这正是它所需要的。这就是为什么在ArrayList
中收集所有内容是一种效率极低但又快速简单的折衷方法。(访客模式将非常有效。)@Aragorn300好的,非常抱歉,我考虑了更多,(在我的答案被投票通过并被接受后),我想出了一个更好的解决方案,只需要搜索第一个出现的,然后只收集重复的。现在这是有意义的!谢谢你的调整。我能让代码正常工作。如果我能投你两次票,我会的@很高兴能帮上忙。我刷牙时,这个问题一直困扰着我,所以我不得不在睡觉前回去回答。
public Collection<File> findAndCollectDuplicates( Node<File> root, File f )
{
/* find a matching node; if none found, return an empty collection. */
Node<File> node = findNode( root, f );
if( node == null )
return Collections.emptyList();
/* collect duplicates and return them. */
List<File> duplicates = new ArrayList<>();
collectDuplicates( node, f, duplicates );
return duplicates;
}
private Node<File> findNode( Node<File> root, File f )
{
for(;;)
{
int result = f.compareTo( root.data );
if (result == 0)
return root;
root = result < 0? root.leftChild : root.rightChild;
if( root == null )
return null;
}
}
private void collectDuplicates( Node<File> node, File f, Collection<File> duplicates )
{
if( node == null )
return;
if( f.compareTo( node.data ) != 0 )
return;
duplicates.add( node.data );
collectDuplicates( node.leftChild );
collectDuplicates( node.rightChild );
}