All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.st.bst.lxx.LLRedBlackBST Maven / Gradle / Ivy

package shz.st.bst.lxx;

/**
 * 健为K类型,值为V类型的红黑树
 * 

* 8+[53+V(类型字节)+K(类型字节)+对齐填充]*n(n为元素个数) *

* B=24+48*n+(5+V+K+对齐填充)*n */ public class LLRedBlackBST, V> extends LXXRedBlackBST { /** * 8+V(类型字节)+29+K(类型字节)+对齐填充 *

* B=53+V(类型字节)+K(类型字节)+对齐填充 */ protected static final class Node, V> extends LXXRedBlackBST.Node { public V val; public Node(K key, V val, boolean red) { super(key, red); this.val = val; } public Node(K key, V val) { this(key, val, true); } } protected LLRedBlackBST(K key, V val) { super(new Node<>(key, val, false)); } public static , V> LLRedBlackBST of(K key, V val) { if (key == null) throw new NullPointerException(); return new LLRedBlackBST<>(key, val); } public static , V> LLRedBlackBST of(K key) { return of(key, null); } public final void put(K key, V val) { if (key == null) throw new NullPointerException(); root = put(root(), key, val); root.red = false; } protected final Node put(Node h, K key, V val) { if (h == null) return new Node<>(key, val); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left(), key, val); else if (cmp > 0) h.right = put(h.right(), key, val); else h.val = val; //如果右子结点是红色的而左子结点是黑色的,进行左旋转 if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); //如果左子结点是红色的且它的左子结点也是红色的,进行右旋转 if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); //如果左右子结点均为红色,进行颜色转换 if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } public final V get(K key) { if (key == null) throw new NullPointerException(); Node h = get(root(), key); return h == null ? null : h.val; } protected final Node get(Node h, K key) { while (h != null) { int cmp = key.compareTo(h.key); if (cmp == 0) break; h = cmp < 0 ? h.left() : h.right(); } return h; } public final void delete(K key) { if (key == null) throw new NullPointerException(); if (root == null) return; if (!isRed(root.left) && !isRed(root.right)) root.red = true; root = delete(root(), key); if (root == null) return; if (!isEmpty()) root.red = false; } protected final Node delete(Node h, K key) { int cmp = key.compareTo(h.key); if (cmp < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left(), key); } else { if (isRed(h.left)) h = rotateRight(h); if (cmp == 0 && h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (cmp == 0) { Node min = min(h.right); h.val = get(h.right(), min.key).val; h.key = min.key; h.right = deleteMin(h.right); } else h.right = delete(h.right(), key); } return balance(h); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy