红黑树的Java实现

来源:互联网 发布:文爱交友软件 编辑:程序博客网 时间:2024/05/11 04:54

参考文章:红黑树原理及代码
本文只有代码,想学习原理的可以看上面的Blog

红黑树的原理并不是很难,添加和删除操作如果只考虑左侧一共就只有7种情况【添加三种,删除四种】

感谢大佬。前人挖井,后人吃水。

代码:

//结点public class TreeNode<T extends Comparable<T>> {    boolean color = true;    T value;    TreeNode<T> parent;    TreeNode<T> left;    TreeNode<T> right;    TreeNode(T value) {        this.value = value;    }    @Override    public String toString() {        return "" + value + (color ? " red" : " black");    }}
//红黑树public class RBTree<T extends Comparable<T> > {    public static final boolean RED = true;    public static final boolean BLACK = false;    TreeNode<T> root;    public TreeNode<T> insertNode(T x) {       return root = InsertManager.insertNode(this, new TreeNode<T>(x));    }    public TreeNode<T> removeNode(T x) {        return root = RemoveManager.removeNode(this, new TreeNode<T>(x));    }    public void print() {        if(root != null) {            print(root, root.value, 0);        }    }    private void print(TreeNode<T> tree, T key, int direction) {        if(tree != null) {            if(direction==0)                System.out.printf("%2d(B) is root\n", tree.value);            else                System.out.printf("%2d(%s) is %2d's %6s child\n", tree.value, tree.color?"R":"B", key, direction==1?"right" : "left");            print(tree.left, tree.value, -1);            print(tree.right,tree.value,  1);        }    }}
//工具类[左旋和右旋]package com.sdkd.hms;import sun.reflect.generics.tree.Tree;/** * Created by hms on 2017/2/28. */public class BalanceUtils {    public static <T extends Comparable<T>> TreeNode<T> leftRoute(RBTree<T> t, TreeNode<T> x) {       TreeNode<T> xr = x.right;       if(xr != null) {           TreeNode<T> xrl = xr.left;           x.right = xrl;           if(xrl != null)               xrl.parent = x.right;           xr.parent = x.parent;           if(x.parent == null) {               t.root = xr;           } else if(x.parent.left == x){               x.parent.left = xr;           } else if(x.parent.right == x){               x.parent.right = xr;           }           xr.left = x;           x.parent = xr;       }       t.root.color = RBTree.BLACK;       return t.root;    }    public static <T extends Comparable<T>> TreeNode<T> rightRoute(RBTree<T> t, TreeNode<T> x) {       TreeNode<T> xl = x.left;       if(xl != null) {           TreeNode<T> xlr = xl.right;           x.left = xlr;           if(xlr != null)               xlr.parent = x;           xl.parent = x.parent;           if(x.parent == null){               t.root = xl;           } else if(x.parent.left == x) {               x.parent.left = xl;           } else if(x.parent.right == x) {               x.parent.right = xl;           }           xl.right = x;           x.parent = xl;       }       t.root.color = RBTree.BLACK;       return t.root;    }}
//负责插入public class InsertManager {    public static<T extends Comparable<T>>  TreeNode<T> insertNode(RBTree<T> t, TreeNode<T> x) {        TreeNode<T> p = null;        TreeNode<T> r = t.root;        while (r != null) {            int cmp = r.value.compareTo(x.value);            if(cmp > 0) {                if(r.left == null) { r.left = x; break;}                else r = r.left;            } else {                if(r.right == null){ r.right = x; break; }                else r = r.right;            }        }        x.parent = r;        if(r == null) {            x.color = RBTree.BLACK;            t.root = x;        }        t.root = BalanceInsert.balanceInsertion(t, x);        return t.root;    }}
//平衡插入public class BalanceInsert {    public static <T extends Comparable<T>> TreeNode<T> balanceInsertion(RBTree<T> t, TreeNode<T> x) {        TreeNode<T> xp = null;        while ((xp  = x.parent)!= null && xp.color == RED) {            TreeNode<T> xpp = xp.parent;            /*             *父节点是祖父结点的左孩子             */            if(xpp != null && xpp.left == xp) {                TreeNode<T> xppr = xpp.right;                if(xppr != null && xppr.color == RED) {                    xp.color = BLACK;                    xppr.color = BLACK;                    xpp.color = RED;                    x = xpp;                    continue;                } else if(xppr == null ||(xppr != null && xppr.color == BLACK)) {                    if(xp.right == x) {                        t.root = BalanceUtils.leftRoute(t, xp);                        TreeNode<T> tmp;                        tmp = xp;                        xp = x;                        x = tmp;                    }                    xp.color = RBTree.BLACK;                    xpp.color = RBTree.RED;                    t.root = BalanceUtils.rightRoute(t, xpp);                }            }            /*             *父节点是祖父节点的右孩子             */            else if(xpp != null && xpp.right == xp) {                TreeNode<T> xppl = xpp.left;                if(xppl != null && xppl.color == RED) {                    xp.color = BLACK;                    xppl.color = BLACK;                    xpp.color = RED;                    x = xpp;                    continue;                } else if(xppl == null ||(xppl != null && xppl.color == BLACK)) {                    if(xp.left == x) {                        t.root = BalanceUtils.rightRoute(t, xp);                        TreeNode<T> tmp;                        tmp = xp;                        xp = x;                        x = tmp;                    }                    xp.color = RBTree.BLACK;                    xpp.color = RBTree.RED;                    t.root = BalanceUtils.leftRoute(t, xpp);                }            }        }        return t.root;    }}
//负责删除package com.sdkd.hms;import sun.reflect.generics.tree.Tree;/** * Created by hms on 2017/2/28. */public class RemoveManager {    public static <T extends Comparable<T>> TreeNode<T> removeNode(RBTree<T> t, TreeNode<T> x) {        TreeNode<T> r = t.root;        while(r != null) {            int cmp = r.value.compareTo(x.value);            if(cmp > 0) r = r.left;            else if(cmp < 0) r = r.right;            else if(cmp == 0){                x = r;                break;            }        }        if(r == null) return t.root;        TreeNode<T> c = null, p = null;        boolean color;        if(x.left != null && x.right != null) {            TreeNode<T> replace = x.right;            while(replace.left != null) replace = replace.left;            if(x.parent == null) {                t.root = replace;            } else if(x.parent !=null && x.parent.left == x) {                x.parent.left = replace;            } else if(x.parent != null && x.parent.right == x) {                x.parent.right = replace;            }            c = replace.right;            p = replace.parent;            color = replace.color;            if(p == x) {                p = replace;            } else{                if(c != null) {                    c.parent = p;                }                p.left = c;                replace.right = x.right;                x.right.parent = replace;            }            replace.parent = x.parent;            replace.color = x.color;            replace.left = x.left;            x.left.parent = replace;            if(color == RBTree.BLACK) {               t.root =  BlanceRemove.balanceRemovtion(t, c, p);            }            x = null;            return t.root;        }        if(x.left != null) c = x.left;        else c = x.right;        color = x.color;        p = x.parent;        if(c != null) c.parent = p;        if(p != null) {            if(p.left == x) {                p.left = c;            } else if(p.right == x) {                p.right = c;            }        } else if(p == null) {            t.root = c;        }        if(color == RBTree.BLACK) {            t.root = BlanceRemove.balanceRemovtion(t, c, p);        }        if(t.root != null)               t.root.color = RBTree.BLACK;        x = null;        return t.root;    }}
//平衡删除package com.sdkd.hms;/** * Created by hms on 2017/2/28. */public class BlanceRemove {    public static <T extends Comparable<T>> TreeNode<T> balanceRemovtion(RBTree<T> t, TreeNode<T> x, TreeNode<T> p){        TreeNode<T> b;        while((x == null || x.color == RBTree.BLACK) && x != t.root) {            if(p.left == x) {                b = p.right;                if(b.color == RBTree.RED) {                    b.color = RBTree.RED;                    p.color = RBTree.RED;                    t.root = BalanceUtils.leftRoute(t,p);                    b = p.right;                }                if( b!=null && (b.left == null || b.left.color == RBTree.BLACK) &&                        (b.right == null || b.right.color == RBTree.BLACK)) {                    b.color = RBTree.RED;                    x = p;                    p = x.parent;                } else {                    if(b !=null && (b.right == null || b.right.color == RBTree.BLACK)) {                        b.left.color = RBTree.BLACK;                        b.color = RBTree.RED;                        t.root = RemoveManager.removeNode(t, b);                        b = p.right;                    }                    if(b !=null) {                        b.color = p.color;                        p.color = RBTree.BLACK;                        b.right.color = RBTree.BLACK;                        t.root = BalanceUtils.rightRoute(t, p);                    }                    break;                }            } else if(p.right == x){                b = p.left;                if(b.color == RBTree.RED) {                    b.color = RBTree.BLACK;                    p.color = RBTree.RED;                    t.root = BalanceUtils.rightRoute(t, p);                    b = p.left;                }                if( b != null && (b.left == null || b.left.color == RBTree.BLACK) &&                        (b.right == null || b.right.color == RBTree.BLACK)) {                    b.color = RBTree.RED;                    x = p;                    p = x.parent;                } else {                    if(b != null && (b.left == null || b.left.color == RBTree.BLACK)){                        b.right.color = RBTree.BLACK;                        b.color = RBTree.RED;                        t.root = BalanceUtils.leftRoute(t, b);                        b = p.left;                    }                    if(b !=null){                        b.color = p.color;                        p.color = RBTree.BLACK;                        b.left.color = RBTree.BLACK;                        t.root = BalanceUtils.rightRoute(t, p);                    }                    break;                }            }        }        if(x != null) x.color = RBTree.BLACK;        return t.root;    }}
//Testpackage com.sdkd.hms;/** * Created by hms on 2017/2/28. */public class Test {    private static final int a[] = {10 ,40 ,30 ,60 ,90 ,70 ,20 ,50 ,80};    private static final boolean mDebugInsert = true;    // "插入"动作的检测开关(false,关闭;true,打开)    private static final boolean mDebugDelete = true;    // "删除"动作的检测开关(false,关闭;true,打开)    public static void main(String[] args) {        int i, ilen = a.length;        RBTree<Integer> tree = new RBTree<Integer>();        System.out.printf("原始数据: ");        for (i = 0; i < ilen; i++)            System.out.printf("%d ", a[i]);        System.out.printf("\n");        for (i = 0; i < ilen; i++) {            System.out.printf("==================================\n");            tree.insertNode(new Integer(a[i]));            // 设置mDebugInsert=true,测试"添加函数"            if (mDebugInsert) {                System.out.printf("添加节点: %d\n", a[i]);                System.out.printf("树的详细信息: \n");                tree.print();                System.out.printf("==================================\n");            }        }        // 设置mDebugDelete=true,测试"删除函数"        if (mDebugDelete) {            for(i=0; i<ilen; i++)            {                tree.removeNode(a[i]);                System.out.printf("删除节点: %d\n", a[i]);                System.out.printf("树的详细信息: \n");                tree.print();                System.out.printf("\n");            }        }    }}
/*Output原始数据: 10 40 30 60 90 70 20 50 80 ==================================添加节点: 10树的详细信息: 10(B) is root====================================================================添加节点: 40树的详细信息: 10(B) is root40(R) is 10's  right child====================================================================添加节点: 30树的详细信息: 30(B) is root10(R) is 30's   left child40(R) is 30's  right child====================================================================添加节点: 60树的详细信息: 30(B) is root10(B) is 30's   left child40(B) is 30's  right child60(R) is 40's  right child====================================================================添加节点: 90树的详细信息: 30(B) is root10(B) is 30's   left child60(B) is 30's  right child40(R) is 60's   left child90(R) is 60's  right child====================================================================添加节点: 70树的详细信息: 30(B) is root10(B) is 30's   left child60(R) is 30's  right child40(B) is 60's   left child90(B) is 60's  right child70(R) is 90's   left child====================================================================添加节点: 20树的详细信息: 30(B) is root10(B) is 30's   left child20(R) is 10's  right child60(R) is 30's  right child40(B) is 60's   left child90(B) is 60's  right child70(R) is 90's   left child====================================================================添加节点: 50树的详细信息: 30(B) is root10(B) is 30's   left child20(R) is 10's  right child60(R) is 30's  right child40(B) is 60's   left child50(R) is 40's  right child90(B) is 60's  right child70(R) is 90's   left child====================================================================添加节点: 80树的详细信息: 30(B) is root10(B) is 30's   left child20(R) is 10's  right child60(R) is 30's  right child40(B) is 60's   left child50(R) is 40's  right child80(B) is 60's  right child70(R) is 80's   left child90(R) is 80's  right child==================================删除节点: 10树的详细信息: 30(B) is root20(B) is 30's   left child60(R) is 30's  right child40(B) is 60's   left child50(R) is 40's  right child80(B) is 60's  right child70(R) is 80's   left child90(R) is 80's  right child删除节点: 40树的详细信息: 30(B) is root20(B) is 30's   left child60(R) is 30's  right child50(B) is 60's   left child80(B) is 60's  right child70(R) is 80's   left child90(R) is 80's  right child删除节点: 30树的详细信息: 50(B) is root20(B) is 50's   left child60(B) is 50's  right child80(R) is 60's  right child70(R) is 80's   left child90(B) is 80's  right child删除节点: 60树的详细信息: 50(B) is root20(B) is 50's   left child80(B) is 50's  right child70(R) is 80's   left child90(B) is 80's  right child删除节点: 90树的详细信息: 50(B) is root20(B) is 50's   left child70(B) is 50's  right child80(R) is 70's  right child删除节点: 70树的详细信息: 50(B) is root20(B) is 50's   left child80(B) is 50's  right child删除节点: 20树的详细信息: 50(B) is root80(R) is 50's  right child删除节点: 50树的详细信息: 80(B) is root删除节点: 80树的详细信息: Process finished with exit code 0
5 0