java - TreeSet/包含方法

标签 java collections treeset

作为练习,我尝试实现自己的 TreeSet。在编写添加和删除方法之前,我更喜欢从 contains 开始,这看起来更容易,但我陷入了困境。

我的树由节点叶子组成:

static class Leaf<E extends Comparable<E>> implements Tree<E> {

                 //stuff
        @Override
        public boolean contains() {
           return false;
        }

}

这是Node 类:

static class Node<E extends Comparable<E>> implements Tree<E> {

    private final E value;
    private Tree<E> left;
    private Tree<E> right;

   //some stuff
   @Override
   public boolean contains(E elem) {
       //here i'm blocked
   }
}

我怎样才能让我的树用元素来查看它的好的部分(左或右)?

最佳答案

使用递归!

正如您所看到的,Leaf 对象构成了Tree 的末尾,因此它将成为该方法的停止条件。

您可以看到,将存储在 Tree 中的对象必须实现 Comparable。所以包含看起来像这样:

@Override
public boolean contains(E elem) {
    int compare = elem.compareTo(value); //here we compare the element with 
                                         //the compareTo method that the objects 
                                         //used must redefined

    if(compare==0)
            return true; //here the current node contains elem !
        else if(compare < 0)
            return left.contains(elem); //elem is inferior than the elem present in the current node hence we look into the left part of the tree
        else
            return right.contains(elem); //elem is superior than the elem present in the current node hence we look into the right part of the tree
    }

如您所见,如果该元素不存在于 Tree 中,我们将位于末尾的 Leaf 中,并且它将返回 false .

您可以对addremove代码实现相同的逻辑

关于java - TreeSet/包含方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16439632/

相关文章:

java - 正则表达式解析可能由或不由 ; 分隔的字符串分成几组

java - 如何使用 gradle + spring boot 1.5 构建子模块的可执行 jar

C# 我应该如何将给定的数据从对象收集到另一个实例?

java - Android 中是否缺少 TreeSet.floor() 和 TreeSet.ceiling() 方法?

Java TreeSet contains() 给出错误的结果

java - Java Set对象可以就地修改吗?

Java uncaughtExceptionHandler 不工作

java - 使用 Collections 方法对类中的特定内容进行排序

java - 一次性将两个 arraylist 合并为一个链表

c# - 如何使用 fluent nhibernate 创建引用表