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

shz.st.bst.ixx.ICRedBlackBST Maven / Gradle / Ivy

package shz.st.bst.ixx;

/**
 * 健为int类型,值为char类型的红黑树
 * 

* 8+48*n(n为元素个数) *

* B=24+48*n */ public class ICRedBlackBST extends IXXRedBlackBST { /** * 2+25+对齐填充=32 *

* B=48 */ protected static final class Node extends IXXRedBlackBST.Node { public char val; public Node(int key, char val, boolean red) { super(key, red); this.val = val; } public Node(int key, char val) { this(key, val, true); } } protected ICRedBlackBST(int key, char val) { super(new Node(key, val, false)); } public static ICRedBlackBST of(int key, char val) { return new ICRedBlackBST(key, val); } public static ICRedBlackBST of(int key) { return of(key, (char) 0); } public final void put(int key, char val) { root = put(root(), key, val); root.red = false; } protected final Node put(Node h, int key, char val) { if (h == null) return new Node(key, val); if (key < h.key) h.left = put(h.left(), key, val); else if (key > h.key) 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 Character get(int key) { Node h = get(root(), key); return h == null ? null : h.val; } protected final Node get(Node h, int key) { while (h != null) { if (key == h.key) break; h = key < h.key ? h.left() : h.right(); } return h; } public final void delete(int key) { 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, int key) { if (key < h.key) { 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 (key == h.key && h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key == h.key) { 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