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

shz.core.st.bst.jxx.JBRedBlackBST Maven / Gradle / Ivy

package shz.core.st.bst.jxx;

/**
 * 健为long类型,值为byte类型的红黑树
 * 

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

* B=24+48*n */ public class JBRedBlackBST extends JXXRedBlackBST { private static final long serialVersionUID = -2556817624240378967L; /** * 1+29+对齐填充=32 *

* B=48 */ protected static final class Node extends JXXRedBlackBST.Node { private static final long serialVersionUID = 4028645566631023947L; public byte val; public Node(long key, byte val, boolean red) { super(key, red); this.val = val; } public Node(long key, byte val) { this(key, val, true); } } protected JBRedBlackBST(long key, byte val) { super(new Node(key, val, false)); } public static JBRedBlackBST of(long key, byte val) { return new JBRedBlackBST(key, val); } public static JBRedBlackBST of(long key) { return of(key, (byte) 0); } public final void put(long key, byte val) { root = put(root, key, val); root.red = false; } protected final Node put(Node h, long key, byte 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 Byte get(long key) { Node h = get(root, key); return h == null ? null : h.val; } protected final Node get(Node h, long key) { while (h != null) { if (key == h.key) break; h = key < h.key ? h.left : h.right; } return h; } public final void delete(long 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, long 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 - 2024 Weber Informatics LLC | Privacy Policy