TreeMap

简述

何为TreeMap?
TreeMap是一个二叉排序树构成的map。

TreeMap怎么实现二叉树的平衡?
红黑树

综上所属TreeMap是一个map + 红黑树的实现。


源码分析

类图

image.png

根据类图可知TreeMap继承AbstractMap和实现了NavigableMap。通过继承AbstractMap来共用父类的非私有方法,便于维护。通过实现了NavigableMap接口来提供一些便利的查询操作。(这是顺序结构通常需要实现的接口)

数据结构

/**
     * 比较器
     */
    private final Comparator comparator;

/**
     * 根节点
     */
    private transient Entry root;

    /**
     * The number of entries in the tree
     */
    private transient int size = 0;

    /**
     * 树节点修改次数
     */
    private transient int modCount = 0;

节点的数据结构

 static final class Entry implements Map.Entry {
        K key;
        V value;
        Entry left;//左节点
        Entry right;//右节点
        Entry parent;//父节点
        boolean color = BLACK;//颜色标记
}

基本操作

put

public V put(K key, V value) {
      Entry t = root;
      //树为空
      if (t == null) {
          compare(key, key); // type (and possibly null) check

          root = new Entry<>(key, value, null);
          size = 1;
          modCount++;
          return null;
      }
      int cmp;
      Entry parent;
      // split comparator and comparable paths
      Comparator cpr = comparator;
      //有默认比较器
      if (cpr != null) {
          do {
              parent = t;
              cmp = cpr.compare(key, t.key);
              if (cmp < 0)
                  t = t.left;
              else if (cmp > 0)
                  t = t.right;
              else
                  return t.setValue(value);
          } while (t != null);
      }
      //无默认比较器
      else {
          if (key == null)
              throw new NullPointerException();
          @SuppressWarnings("unchecked")
              Comparable k = (Comparable) key;
          do {
              parent = t;
              cmp = k.compareTo(t.key);
              if (cmp < 0)
                  t = t.left;
              else if (cmp > 0)
                  t = t.right;
              else
                  return t.setValue(value);
          } while (t != null);
      }
      Entry e = new Entry<>(key, value, parent);
      if (cmp < 0)
          parent.left = e;
      else
          parent.right = e;
      //变树,为了保证平衡
      fixAfterInsertion(e);
      size++;
      modCount++;
      return null;
  }

//插入后维持平衡
private void fixAfterInsertion(Entry x) {
      // 插入的节点为红色节点
      x.color = RED;

      while (x != null && x != root && x.parent.color == RED) {
          //当前节点为左节点
          if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
              Entry y = rightOf(parentOf(parentOf(x)));
              //叔叔节点是红色
              if (colorOf(y) == RED) {
                  setColor(parentOf(x), BLACK);
                  setColor(y, BLACK);
                  setColor(parentOf(parentOf(x)), RED);
                  x = parentOf(parentOf(x));
              } else {//叔叔节点是黑色
                  if (x == rightOf(parentOf(x))) {
                      x = parentOf(x);
                      //左旋
                      rotateLeft(x);
                  }
                  setColor(parentOf(x), BLACK);
                  setColor(parentOf(parentOf(x)), RED);
                  //右旋转
                  rotateRight(parentOf(parentOf(x)));
              }
          } else {
              Entry y = leftOf(parentOf(parentOf(x)));
             //叔叔节点是红色
              if (colorOf(y) == RED) {
                  setColor(parentOf(x), BLACK);
                  setColor(y, BLACK);
                  setColor(parentOf(parentOf(x)), RED);
                  x = parentOf(parentOf(x));
              } else {
                  if (x == leftOf(parentOf(x))) {
                      x = parentOf(x);
                      //右旋转
                      rotateRight(x);
                  }
                  setColor(parentOf(x), BLACK);
                  setColor(parentOf(parentOf(x)), RED);
                  //左旋转
                  rotateLeft(parentOf(parentOf(x)));
              }
          }
      }
      root.color = BLACK;
  }
  • 先通过查找树的方式找到合适的位置把节点放入
  • 新插入的节点可能导致树不平衡
  • 根据红黑树的方式变色、左旋、右旋保证树的平衡

remove

public V remove(Object key) {
        Entry p = getEntry(key);
        if (p == null)
            return null;

        V oldValue = p.value;
        deleteEntry(p);
        return oldValue;
}

public void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            // deleted entries are replaced by their successors
            if (lastReturned.left != null && lastReturned.right != null)
                next = lastReturned;
            deleteEntry(lastReturned);
            expectedModCount = modCount;
            lastReturned = null;
        }
private void deleteEntry(Entry p) {
        modCount++;
        size--;

        // If strictly internal, copy successor's element to p and then make p
        // 如果左右都非空,则找到继承者来代替它的位置
        if (p.left != null && p.right != null) {
            Entry s = successor(p);
            p.key = s.key;
            p.value = s.value;
            p = s;
        } // p has 2 children

        // Start fixup at replacement node, if it exists.
        Entry replacement = (p.left != null ? p.left : p.right);

        if (replacement != null) {
            // Link replacement to parent
            replacement.parent = p.parent;
            if (p.parent == null)
                root = replacement;
            else if (p == p.parent.left)
                p.parent.left  = replacement;
            else
                p.parent.right = replacement;

            // Null out links so they are OK to use by fixAfterDeletion.
            p.left = p.right = p.parent = null;

            // Fix replacement
            if (p.color == BLACK)
                fixAfterDeletion(replacement);
        } else if (p.parent == null) { // return if we are the only node.
            root = null;
        } else { //  No children. Use self as phantom replacement and unlink.
            if (p.color == BLACK)
                fixAfterDeletion(p);

            if (p.parent != null) {
                if (p == p.parent.left)
                    p.parent.left = null;
                else if (p == p.parent.right)
                    p.parent.right = null;
                p.parent = null;
            }
        }
    }

/** From CLR */
    private void fixAfterDeletion(Entry x) {
        while (x != root && colorOf(x) == BLACK) {
            if (x == leftOf(parentOf(x))) {
                Entry sib = rightOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateLeft(parentOf(x));
                    sib = rightOf(parentOf(x));
                }

                if (colorOf(leftOf(sib))  == BLACK &&
                    colorOf(rightOf(sib)) == BLACK) {
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(rightOf(sib)) == BLACK) {
                        setColor(leftOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateRight(sib);
                        sib = rightOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(rightOf(sib), BLACK);
                    rotateLeft(parentOf(x));
                    x = root;
                }
            } else { // symmetric
                Entry sib = leftOf(parentOf(x));

                if (colorOf(sib) == RED) {
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateRight(parentOf(x));
                    sib = leftOf(parentOf(x));
                }

                if (colorOf(rightOf(sib)) == BLACK &&
                    colorOf(leftOf(sib)) == BLACK) {
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
                    if (colorOf(leftOf(sib)) == BLACK) {
                        setColor(rightOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateLeft(sib);
                        sib = leftOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(leftOf(sib), BLACK);
                    rotateRight(parentOf(x));
                    x = root;
                }
            }
        }

        setColor(x, BLACK);
    }
  • 找到需要删除的节点
  • 找到它的字节点中能够替换它的节点
  • 变树保持平衡

常见问题

树的结构有何优点?
与线性表对比,线性表的平均查找次数=n/2,平衡二叉树平均查找次数=logn。线性表查找只有在极小的数据量下才会有优势。
与hash对比,在查看速度看树可能比不上hash结构。但是二叉树的结构为范围检索提供了方便。

有几种平衡树
二叉树:AVL树、红黑树
n叉树:B-树、B+树

你可能感兴趣的:(TreeMap)