001 数据结构与算法 之 红黑树 的应用


1、红黑树的使用场景

(1)JDK TreeSet、TreeMap、JDK1.8 HashMap

(2)Java NIO编程Epoll底层数据结构使用了红黑树

(3)c++红黑树广泛的使用在STL中

对于TreeSet,看源码,本质是TreeMap。

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{
    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    /**
     * Constructs a set backed by the specified navigable map.
     */
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

    /**
     * Constructs a new, empty tree set, sorted according to the
     * natural ordering of its elements.  All elements inserted into
     * the set must implement the {@link Comparable} interface.
     * Furthermore, all such elements must be <i>mutually
     * comparable</i>: {@code e1.compareTo(e2)} must not throw a
     * {@code ClassCastException} for any elements {@code e1} and
     * {@code e2} in the set.  If the user attempts to add an element
     * to the set that violates this constraint (for example, the user
     * attempts to add a string element to a set whose elements are
     * integers), the {@code add} call will throw a
     * {@code ClassCastException}.
     */
    public TreeSet() {
	this(new TreeMap<E,Object>());
    }

其内部是是用了TreeMap,Set值保存在Map的key中,value存了一个Object,Map中如果Key值相同会被认为是同一个,这样就能够实现数据去重。TreeMap内部维护的是一个红黑树。因为是树状结果,那么其查询效率和插入效率都是log(n),当然对应耗时会因为红黑树平衡调整,会有相应的耗时。
TreeSet不是线性安全的,线性安全需要使用ConcurrentSkipListSet。内部是SkipList(跳表)结构实现,在理论=上能够实现O(log(n))时间内完成查找、插入、删除操作。

看TreeMap的源码,本质是红黑树的实现(部分源码如下)

/**
 * A Red-Black tree based {@link NavigableMap} implementation.
 * The map is sorted according to the {@linkplain Comparable natural
 * ordering} of its keys, or by a {@link Comparator} provided at map
 * creation time, depending on which constructor is used.
 * 
 */
public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
    public TreeMap() {
        comparator = null;
    }
}

epoll底层实现是红黑树



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值