红5java_关于skywang123456之“红黑树(五)之 Java的实现”的改进与内容添加

其实就是添加两大功能:二叉树绘制与根据数值搜索临近节点。

改进?hhhhh想多了,其实我根本没看懂红黑树的代码,会用,能改就行,反正我是个拿来主义者。

之前拿过skywang123456(以下简称天王)的BSTree二叉树实现,我拿来给一个android video cuttor作时间轴标记之用。

用用改改,已有数月。搜索算法就是那时完成的,而今天我把我的那些代码复制粘贴,只消修改一下节点的类名,ok,毫无错误,完全可以用在红黑树上,hhhh真是愉快的编程体验。

代码已经上传github,现在贴一点代码好了,不然怎么算写博客?     :)

fe1137825b987b50c6b1e25f1080fa3c.png

绘图就是这个样子咯,很简单。

首先,二叉树绘图程序基于源代码的inorder中序遍历算法,这是一个递归算法。

借助于java的接口(interface)特性,我们可以让一个tree以inorder的方式,来执行我们布置的绘图代码。

//定义我们的接口

public interfaceinOrderDo{voiddothis(RBTNode node);

}//![3]中序递归,此处使用接口

private void inOrderDo(RBTNodenode) {if(node != null) {

inOrderDo(node.left);

mInOrderDo.dothis(node);

inOrderDo(node.right);

}

}//![1]公开设置接口的函数

public voidSetInOrderDo(inOrderDo ido){

mInOrderDo=ido;

}private inOrderDo mInOrderDo;//接口的一个对象,是私有的

这样,布置中序执行一些代码只需要:

tree.SetInOrderDo(newinOrderDo(){public voiddothis(RBTNode n) {//……这里布置要中序执行的代码

}

});

tree.inOrderDo();

玩java的话,开发过安卓应用吧?button.setOnClickListener(...)也是接口的一种运用。

如何绘制二叉树?我们在窗口JFrame的内容面板JPanel的绘图call里布置代码。

protected voidpaintComponent(Graphics g) {super.paintComponent(g);

((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

((Graphics2D)g).setColor(Color.RED);final Graphics2D g2 =(Graphics2D)g.create();

g2.setFont(new Font(null, Font.ITALIC, 25));

//这里

tree.SetInOrderDo(newinOrderDo(){public voiddothis(RBTNode n) {

RBTNode n2 = ((RBTNode)n);if(n2.color==true)

g2.setColor(Color.black);elseg2.setColor(Color.red);

g2.drawString(n2.key+"",n2.key*10 ,200);

}});

//和这里

tree.inOrderDo();

}

很简单,我只是根据节点的键值,将节点分散开画在了一条直线上。

运行代码,结果如下:

55581165070af1d0f878430820c628fa.png

如何显示层级的高低关系?这就要求我们知道每一个节点的depth深度值。可以在添加节点的时候写入depth,但是据我所知,为了维持二叉树的平衡性,红黑树算法在插入节点的时候会有旋转操作,不同节点的depth可能会变化。

所以,我在inOrderDo里面自己计算depth值。

public int inorderCounter = 0;public int inorderCounter2 = 0;//![3]中序递归

private void inOrderDo(RBTNodenode) {if(node != null) {

inorderCounter2+=1;

inOrderDo(node.left);

mInOrderDo.dothis(node);

inorderCounter+=1;

inOrderDo(node.right);

inorderCounter2-=1;

}

}

根据逻辑的对称性、优美性,我进行了有趣而大胆的试验,得到如上代码;那么,继而根据实践是检验真理的唯一标准,inorderCounter代表当前节点是第几个绘制(显而易见),而inorderCounter2代表的则是当前节点的层深度——depth值。

为什么?自己悟去吧,或者——

打印出来嘛:

g2.drawString(tree.inorderCounter2+"."+n2.key+"", n2.key*10, 200);

fcb554dc2dea29257c69bddfd90c7c27.png

根节点是40,左右子节点是20、80;那么40的depth是1,20、80的depth是2,完全符合。

从而,根据层深度,我们可以绘制二叉树啦!

g2.drawString(n2.key+"",n2.key*10 ,tree.inorderCoounter2*100);//根据层深度,竖直方向分散开来。

//写博客的时候发现inorderCoounter2拼错了,寒……

我还根据窗口大小计算了比例,这样二叉树可以随窗口缩放而缩放。

当然,此处节点之间的水平距离其完全正比于节点间的键值差,这显然不是最好的做法,在一些情况下会造成重叠,不过目前已经足够。

再说一下搜索函数sxing(T val)和xxing(T val)

abeb9c6869cafe31f2f582eef1c8c64a.png

这两个函数根据val值,向下或者向上去接近,并返回最近的节点。比如xxing(89)向下接近于节点80,并返回节点80。

算法如下:

//下行wrap :find node x,so that x.key=

public RBTNodexxing(T val){

RBTNode tmpnode =downwardNeighbour(this.mRoot,val);if (tmpnode!=null) returntmpnode;else return this.maximum(this.mRoot);

}///情况二///cur///情况一/

private RBTNode downwardNeighbour(RBTNodedu,T val) {intcmp;

RBTNode x =du;

RBTNode tmpnode = null;if (x==null)return null;

cmp=val.compareTo(x.key);if (cmp < 0)//情况一

returndownwardNeighbour(x.left, val);else//if (cmp >= 0)//情况二

{if(x.right==null ) returnx;

tmpnode=downwardNeighbour(x.right, val);if (tmpnode==null) returnx;else returntmpnode;

}

}//上行wrap :find node x,so that x.key>=val and no node with key smaller that x.key satisfies this condition.

public RBTNodesxing(T val){

RBTNode tmpnode =upwardNeighbour(this.mRoot,val);if (tmpnode!=null) returntmpnode;else return this.minimum(this.mRoot);

}///情况一cur///情况二// private RBTNode upwardNeighbour(RBTNodedu,T val) {intcmp;

RBTNode x =du;

RBTNode tmpnode = null;if (x==null)return null;

cmp=val.compareTo(x.key);if (cmp > 0)//情况一

returnupwardNeighbour(x.right, val);else//if (cmp =< 0)//情况二

{if(x.left==null ) returnx;

tmpnode=upwardNeighbour(x.left, val);if (tmpnode==null) returnx;else returntmpnode;

}

}//![END]

这是几个月前写的代码了,搬上来原封不动,除了改类名、去掉等号。

源代码还提供了前驱函数和后继函数,可以与我写的那俩functions配合使用。

System.out.println(tree.xxing(89).key+"");

RBTNode currNode = tree.xxing(89);

System.out.println("前驱节点是:"+tree.successor(currNode).key+"");

System.out.println("后继节点是:"+tree.predecessor(currNode).key+"");

输出:

80前驱节点是:90后继节点是:70

总结:

下行搜索《val《上行搜索

后继节点《curr《前驱节点

ok.终于写完。

完整代码:

RBTree.java

package rbtree;

/**

* Java 语言: 红黑树

*

* @author skywang

* @date 2013/11/07

*/

public class RBTree> {

private RBTNode mRoot; // 根结点

private static final boolean RED = false;

private static final boolean BLACK = true;

public RBTree() {

mRoot=null;

}

private RBTNode parentOf(RBTNode node) {

return node!=null ? node.parent : null;

}

private boolean colorOf(RBTNode node) {

return node!=null ? node.color : BLACK;

}

private boolean isRed(RBTNode node) {

return ((node!=null)&&(node.color==RED)) ? true : false;

}

private boolean isBlack(RBTNode node) {

return !isRed(node);

}

private void setBlack(RBTNode node) {

if (node!=null)

node.color = BLACK;

}

private void setRed(RBTNode node) {

if (node!=null)

node.color = RED;

}

private void setParent(RBTNode node, RBTNode parent) {

if (node!=null)

node.parent = parent;

}

private void setColor(RBTNode node, boolean color) {

if (node!=null)

node.color = color;

}

/*

* 前序遍历"红黑树"

*/

private void preOrder(RBTNode tree) {

if(tree != null) {

System.out.print(tree.key+" ");

preOrder(tree.left);

preOrder(tree.right);

}

}

public void preOrder() {

preOrder(mRoot);

}

/*

* 中序遍历"红黑树"

*/

private void inOrder(RBTNode tree) {

if(tree != null) {

inOrder(tree.left);

System.out.print(tree.key+" ");

inOrder(tree.right);

}

}

public void inOrder() {

inOrder(mRoot);

}

//mycode

public int inorderCoounter = 0;

public int inorderCoounter2 = 0;

//![0]wrap

public void inOrderDo() {

inorderCoounter = 0;//important

inorderCoounter2 = 0;//important

inOrderDo(mRoot);

}

//![1]设置接口

public void SetInOrderDo(inOrderDo ido){

mInOrderDo = ido;

}

//![2]接口

public interface inOrderDo{

void dothis(RBTNode node);

}

private inOrderDo mInOrderDo;

//![3]中序递归

private void inOrderDo(RBTNode node) {

if(node != null) {

inorderCoounter2+=1;

inOrderDo(node.left);

mInOrderDo.dothis(node);

inorderCoounter+=1;

inOrderDo(node.right);

inorderCoounter2-=1;//嘿嘿老子是天才

}

}

//![4]

//![5]此处放大招!!

//下行wrap :find node x,so that x.key=

public RBTNode xxing(T val){

RBTNode tmpnode =downwardNeighbour(this.mRoot,val);

if (tmpnode!=null) return tmpnode;

else return this.maximum(this.mRoot);

}

///情况二///cur///情况一/

private RBTNode downwardNeighbour(RBTNode du,T val) {

int cmp;

RBTNode x = du;

RBTNode tmpnode = null;

if (x==null)

return null;

cmp = val.compareTo(x.key);

if (cmp < 0)//情况一

return downwardNeighbour(x.left, val);

else// if (cmp >= 0)//情况二

{

if(x.right==null ) return x;

tmpnode = downwardNeighbour(x.right, val);

if (tmpnode==null) return x;

else return tmpnode;

}

}

//上行wrap :find node x,so that x.key>=val and no node with key smaller that x.key satisfies this condition.

public RBTNode sxing(T val){

RBTNode tmpnode =upwardNeighbour(this.mRoot,val);

if (tmpnode!=null) return tmpnode;

else return this.minimum(this.mRoot);

}

///情况一cur///情况二//

private RBTNode upwardNeighbour(RBTNode du,T val) {

int cmp;

RBTNode x = du;

RBTNode tmpnode = null;

if (x==null)

return null;

cmp = val.compareTo(x.key);

if (cmp > 0)//情况一

return upwardNeighbour(x.right, val);

else// if (cmp =< 0)//情况二

{

if(x.left==null ) return x;

tmpnode = upwardNeighbour(x.left, val);

if (tmpnode==null) return x;

else return tmpnode;

}

}

//![END]

/*

* 后序遍历"红黑树"

*/

private void postOrder(RBTNode tree) {

if(tree != null)

{

postOrder(tree.left);

postOrder(tree.right);

System.out.print(tree.key+" ");

}

}

public void postOrder() {

postOrder(mRoot);

}

/*

* (递归实现)查找"红黑树x"中键值为key的节点

*/

private RBTNode search(RBTNode x, T key) {

if (x==null)

return x;

int cmp = key.compareTo(x.key);

if (cmp < 0)

return search(x.left, key);

else if (cmp > 0)

return search(x.right, key);

else

return x;

}

public RBTNode search(T key) {

return search(mRoot, key);

}

/*

* (非递归实现)查找"红黑树x"中键值为key的节点

*/

private RBTNode iterativeSearch(RBTNode x, T key) {

while (x!=null) {

int cmp = key.compareTo(x.key);

if (cmp < 0)

x = x.left;

else if (cmp > 0)

x = x.right;

else

return x;

}

return x;

}

public RBTNode iterativeSearch(T key) {

return iterativeSearch(mRoot, key);

}

/*

* 查找最小结点:返回tree为根结点的红黑树的最小结点。

*/

private RBTNode minimum(RBTNode tree) {

if (tree == null)

return null;

while(tree.left != null)

tree = tree.left;

return tree;

}

public T minimum() {

RBTNode p = minimum(mRoot);

if (p != null)

return p.key;

return null;

}

/*

* 查找最大结点:返回tree为根结点的红黑树的最大结点。

*/

private RBTNode maximum(RBTNode tree) {

if (tree == null)

return null;

while(tree.right != null)

tree = tree.right;

return tree;

}

public T maximum() {

RBTNode p = maximum(mRoot);

if (p != null)

return p.key;

return null;

}

/*

* 找结点(x)的后继结点。即,查找"红黑树中数据值大于该结点"的"最小结点"。

*/

public RBTNode successor(RBTNode x) {

// 如果x存在右孩子,则"x的后继结点"为 "以其右孩子为根的子树的最小结点"。

if (x.right != null)

return minimum(x.right);

// 如果x没有右孩子。则x有以下两种可能:

// (01) x是"一个左孩子",则"x的后继结点"为 "它的父结点"。

// (02) x是"一个右孩子",则查找"x的最低的父结点,并且该父结点要具有左孩子",找到的这个"最低的父结点"就是"x的后继结点"。

RBTNode y = x.parent;

while ((y!=null) && (x==y.right)) {

x = y;

y = y.parent;

}

return y;

}

/*

* 找结点(x)的前驱结点。即,查找"红黑树中数据值小于该结点"的"最大结点"。

*/

public RBTNode predecessor(RBTNode x) {

// 如果x存在左孩子,则"x的前驱结点"为 "以其左孩子为根的子树的最大结点"。

if (x.left != null)

return maximum(x.left);

// 如果x没有左孩子。则x有以下两种可能:

// (01) x是"一个右孩子",则"x的前驱结点"为 "它的父结点"。

// (01) x是"一个左孩子",则查找"x的最低的父结点,并且该父结点要具有右孩子",找到的这个"最低的父结点"就是"x的前驱结点"。

RBTNode y = x.parent;

while ((y!=null) && (x==y.left)) {

x = y;

y = y.parent;

}

return y;

}

/*

* 对红黑树的节点(x)进行左旋转

*

* 左旋示意图(对节点x进行左旋):

* px px

* / /

* x y

* / \ --(左旋)-. / \ #

* lx y x ry

* / \ / \

* ly ry lx ly

*

*

*/

private void leftRotate(RBTNode x) {

// 设置x的右孩子为y

RBTNode y = x.right;

// 将 “y的左孩子” 设为 “x的右孩子”;

// 如果y的左孩子非空,将 “x” 设为 “y的左孩子的父亲”

x.right = y.left;

if (y.left != null)

y.left.parent = x;

// 将 “x的父亲” 设为 “y的父亲”

y.parent = x.parent;

if (x.parent == null) {

this.mRoot = y; // 如果 “x的父亲” 是空节点,则将y设为根节点

} else {

if (x.parent.left == x)

x.parent.left = y; // 如果 x是它父节点的左孩子,则将y设为“x的父节点的左孩子”

else

x.parent.right = y; // 如果 x是它父节点的左孩子,则将y设为“x的父节点的左孩子”

}

// 将 “x” 设为 “y的左孩子”

y.left = x;

// 将 “x的父节点” 设为 “y”

x.parent = y;

}

/*

* 对红黑树的节点(y)进行右旋转

*

* 右旋示意图(对节点y进行左旋):

* py py

* / /

* y x

* / \ --(右旋)-. / \ #

* x ry lx y

* / \ / \ #

* lx rx rx ry

*

*/

public void rrt(){//hmm...just for test(may crash)

rightRotate(mRoot);

}

private void rightRotate(RBTNode y) {

// 设置x是当前节点的左孩子。

RBTNode x = y.left;

// 将 “x的右孩子” 设为 “y的左孩子”;

// 如果"x的右孩子"不为空的话,将 “y” 设为 “x的右孩子的父亲”

y.left = x.right;

if (x.right != null)

x.right.parent = y;

// 将 “y的父亲” 设为 “x的父亲”

x.parent = y.parent;

if (y.parent == null) {

this.mRoot = x; // 如果 “y的父亲” 是空节点,则将x设为根节点

} else {

if (y == y.parent.right)

y.parent.right = x; // 如果 y是它父节点的右孩子,则将x设为“y的父节点的右孩子”

else

y.parent.left = x; // (y是它父节点的左孩子) 将x设为“x的父节点的左孩子”

}

// 将 “y” 设为 “x的右孩子”

x.right = y;

// 将 “y的父节点” 设为 “x”

y.parent = x;

}

/*

* 红黑树插入修正函数

*

* 在向红黑树中插入节点之后(失去平衡),再调用该函数;

* 目的是将它重新塑造成一颗红黑树。

*

* 参数说明:

* node 插入的结点 // 对应《算法导论》中的z

*/

private void insertFixUp(RBTNode node) {

RBTNode parent, gparent;

// 若“父节点存在,并且父节点的颜色是红色”

while (((parent = parentOf(node))!=null) && isRed(parent)) {

gparent = parentOf(parent);

//若“父节点”是“祖父节点的左孩子”

if (parent == gparent.left) {

// Case 1条件:叔叔节点是红色

RBTNode uncle = gparent.right;

if ((uncle!=null) && isRed(uncle)) {

setBlack(uncle);

setBlack(parent);

setRed(gparent);

node = gparent;

continue;

}

// Case 2条件:叔叔是黑色,且当前节点是右孩子

if (parent.right == node) {

RBTNode tmp;

leftRotate(parent);

tmp = parent;

parent = node;

node = tmp;

}

// Case 3条件:叔叔是黑色,且当前节点是左孩子。

setBlack(parent);

setRed(gparent);

rightRotate(gparent);

} else { //若“z的父节点”是“z的祖父节点的右孩子”

// Case 1条件:叔叔节点是红色

RBTNode uncle = gparent.left;

if ((uncle!=null) && isRed(uncle)) {

setBlack(uncle);

setBlack(parent);

setRed(gparent);

node = gparent;

continue;

}

// Case 2条件:叔叔是黑色,且当前节点是左孩子

if (parent.left == node) {

RBTNode tmp;

rightRotate(parent);

tmp = parent;

parent = node;

node = tmp;

}

// Case 3条件:叔叔是黑色,且当前节点是右孩子。

setBlack(parent);

setRed(gparent);

leftRotate(gparent);

}

}

// 将根节点设为黑色

setBlack(this.mRoot);

}

/*

* 将结点插入到红黑树中

*

* 参数说明:

* node 插入的结点 // 对应《算法导论》中的node

*/

private void insert(RBTNode node) {

int cmp;

RBTNode y = null;

RBTNode x = this.mRoot;

// 1. 将红黑树当作一颗二叉查找树,将节点添加到二叉查找树中。

while (x != null) {

y = x;

cmp = node.key.compareTo(x.key);

if (cmp < 0)

x = x.left;

else

x = x.right;

}

node.parent = y;

if (y!=null) {

cmp = node.key.compareTo(y.key);

if (cmp < 0)

y.left = node;

else

y.right = node;

} else {

this.mRoot = node;

}

// 2. 设置节点的颜色为红色

node.color = RED;

// 3. 将它重新修正为一颗二叉查找树

insertFixUp(node);

}

/*

* 新建结点(key),并将其插入到红黑树中

*

* 参数说明:

* key 插入结点的键值

*/

public void insert(T key) {

RBTNode node=new RBTNode(key,BLACK,null,null,null);

// 如果新建结点失败,则返回。

if (node != null)

insert(node);

}

/*

* 红黑树删除修正函数

*

* 在从红黑树中删除插入节点之后(红黑树失去平衡),再调用该函数;

* 目的是将它重新塑造成一颗红黑树。

*

* 参数说明:

* node 待修正的节点

*/

private void removeFixUp(RBTNode node, RBTNode parent) {

RBTNode other;

while ((node==null || isBlack(node)) && (node != this.mRoot)) {

if (parent.left == node) {

other = parent.right;

if (isRed(other)) {

// Case 1: x的兄弟w是红色的

setBlack(other);

setRed(parent);

leftRotate(parent);

other = parent.right;

}

if ((other.left==null || isBlack(other.left)) &&

(other.right==null || isBlack(other.right))) {

// Case 2: x的兄弟w是黑色,且w的俩个孩子也都是黑色的

setRed(other);

node = parent;

parent = parentOf(node);

} else {

if (other.right==null || isBlack(other.right)) {

// Case 3: x的兄弟w是黑色的,并且w的左孩子是红色,右孩子为黑色。

setBlack(other.left);

setRed(other);

rightRotate(other);

other = parent.right;

}

// Case 4: x的兄弟w是黑色的;并且w的右孩子是红色的,左孩子任意颜色。

setColor(other, colorOf(parent));

setBlack(parent);

setBlack(other.right);

leftRotate(parent);

node = this.mRoot;

break;

}

} else {

other = parent.left;

if (isRed(other)) {

// Case 1: x的兄弟w是红色的

setBlack(other);

setRed(parent);

rightRotate(parent);

other = parent.left;

}

if ((other.left==null || isBlack(other.left)) &&

(other.right==null || isBlack(other.right))) {

// Case 2: x的兄弟w是黑色,且w的俩个孩子也都是黑色的

setRed(other);

node = parent;

parent = parentOf(node);

} else {

if (other.left==null || isBlack(other.left)) {

// Case 3: x的兄弟w是黑色的,并且w的左孩子是红色,右孩子为黑色。

setBlack(other.right);

setRed(other);

leftRotate(other);

other = parent.left;

}

// Case 4: x的兄弟w是黑色的;并且w的右孩子是红色的,左孩子任意颜色。

setColor(other, colorOf(parent));

setBlack(parent);

setBlack(other.left);

rightRotate(parent);

node = this.mRoot;

break;

}

}

}

if (node!=null)

setBlack(node);

}

/*

* 删除结点(node),并返回被删除的结点

*

* 参数说明:

* node 删除的结点

*/

private void remove(RBTNode node) {

RBTNode child, parent;

boolean color;

// 被删除节点的"左右孩子都不为空"的情况。

if ( (node.left!=null) && (node.right!=null) ) {

// 被删节点的后继节点。(称为"取代节点")

// 用它来取代"被删节点"的位置,然后再将"被删节点"去掉。

RBTNode replace = node;

// 获取后继节点

replace = replace.right;

while (replace.left != null)

replace = replace.left;

// "node节点"不是根节点(只有根节点不存在父节点)

if (parentOf(node)!=null) {

if (parentOf(node).left == node)

parentOf(node).left = replace;

else

parentOf(node).right = replace;

} else {

// "node节点"是根节点,更新根节点。

this.mRoot = replace;

}

// child是"取代节点"的右孩子,也是需要"调整的节点"。

// "取代节点"肯定不存在左孩子!因为它是一个后继节点。

child = replace.right;

parent = parentOf(replace);

// 保存"取代节点"的颜色

color = colorOf(replace);

// "被删除节点"是"它的后继节点的父节点"

if (parent == node) {

parent = replace;

} else {

// child不为空

if (child!=null)

setParent(child, parent);

parent.left = child;

replace.right = node.right;

setParent(node.right, replace);

}

replace.parent = node.parent;

replace.color = node.color;

replace.left = node.left;

node.left.parent = replace;

if (color == BLACK)

removeFixUp(child, parent);

node = null;

return ;

}

if (node.left !=null) {

child = node.left;

} else {

child = node.right;

}

parent = node.parent;

// 保存"取代节点"的颜色

color = node.color;

if (child!=null)

child.parent = parent;

// "node节点"不是根节点

if (parent!=null) {

if (parent.left == node)

parent.left = child;

else

parent.right = child;

} else {

this.mRoot = child;

}

if (color == BLACK)

removeFixUp(child, parent);

node = null;

}

/*

* 删除结点(z),并返回被删除的结点

*

* 参数说明:

* tree 红黑树的根结点

* z 删除的结点

*/

public void remove(T key) {

RBTNode node;

if ((node = search(mRoot, key)) != null)

remove(node);

}

/*

* 销毁红黑树

*/

private void destroy(RBTNode tree) {

if (tree==null)

return ;

if (tree.left != null)

destroy(tree.left);

if (tree.right != null)

destroy(tree.right);

tree=null;

}

public void clear() {

destroy(mRoot);

mRoot = null;

}

/*

* 打印"红黑树"

*

* key -- 节点的键值

* direction -- 0,表示该节点是根节点;

* -1,表示该节点是它的父结点的左孩子;

* 1,表示该节点是它的父结点的右孩子。

*/

private void print(RBTNode tree, T key, int direction) {

if(tree != null) {

if(direction==0) // tree是根节点

System.out.printf("%2d(B) is root\n", tree.key);

else // tree是分支节点

System.out.printf("%2d(%s) is %2d's %6s child\n", tree.key, isRed(tree)?"R":"B", key, direction==1?"right" : "left");

print(tree.left, tree.key, -1);

print(tree.right,tree.key, 1);

}

}

public void print() {

if (mRoot != null)

print(mRoot, mRoot.key, 0);

}

}

RBTNode.java

package rbtree;

public class RBTNode> {

private static final boolean RED = false;

private static final boolean BLACK = true;

boolean color; // 颜色

T key; // 关键字(键值)

RBTNode left; // 左孩子

RBTNode right; // 右孩子

RBTNode parent; // 父结点

public RBTNode(T key, boolean color, RBTNode parent, RBTNode left, RBTNode right) {

this.key = key;

this.color = color;

this.parent = parent;

this.left = left;

this.right = right;

}

public T getKey() {

return key;

}

public String toString() {

return ""+key+(this.color==RED?"(R)":"B");

}

}

测试程序RBTreeTest.java:

package rbtree;

import java.awt.BasicStroke;

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.RenderingHints;

import java.awt.Toolkit;

import java.util.Random;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.WindowConstants;

import rbtree.RBTree.inOrderDo;

/**

* Java 语言: 二叉查找树

*

* @author skywang

* @date 2013/11/07

*/

public class RBTreeTest {

static RBTree tree;

private static final int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90,100,110,120};

private static final boolean mDebugInsert = false; // "插入"动作的检测开关(false,关闭;true,打开)

private static final boolean mDebugDelete = false; // "删除"动作的检测开关(false,关闭;true,打开)

public static void main(String[] args) {

int i, ilen = a.length;

tree=new RBTree();

System.out.printf("== 原始数据: ");

for(i=0; i

System.out.printf("%d ", a[i]);

System.out.printf("\n");

for(i=0; i

tree.insert(a[i]);

// 设置mDebugInsert=true,测试"添加函数"

if (mDebugInsert) {

System.out.printf("== 添加节点: %d\n", a[i]);

System.out.printf("== 树的详细信息: \n");

tree.print();

System.out.printf("\n");

}

}

System.out.printf("== 前序遍历: ");

//tree.preOrder();

System.out.printf("\n== 中序遍历: ");

//tree.inOrder();

System.out.printf("\n== 后序遍历: ");

//tree.postOrder();

System.out.printf("\n");

System.out.printf("== 最小值: %s\n", tree.minimum());

System.out.printf("== 最大值: %s\n", tree.maximum());

System.out.printf("== 树的详细信息: \n");

tree.print();

System.out.printf("\n");

// 设置mDebugDelete=true,测试"删除函数"

if (mDebugDelete) {

for(i=0; i

{

tree.remove(a[i]);

System.out.printf("== 删除节点: %d\n", a[i]);

System.out.printf("== 树的详细信息: \n");

tree.print();

System.out.printf("\n");

}

}

//mycode

Random ra =new Random();

long start=System.currentTimeMillis(); //获取开始时间

//for(i=0; i<10000000; i++)

//tree.insert(i);

long end=System.currentTimeMillis(); //获取结束时间

System.out.println("addition时间: "+(end-start)+"ms");

System.out.println("addition done...");

//System.out.println(tree.search(100).key+"");

start=System.currentTimeMillis(); //获取开始时间

System.out.println(tree.xxing(99).key+"");

end=System.currentTimeMillis(); //获取结束时间

System.out.println("程序运行时间: "+(end-start)+"ms");

System.out.println(tree.xxing(90).key+"");

System.out.println(tree.xxing(89).key+"");

RBTNode currNode = tree.xxing(89);

System.out.println("前驱节点是:"+tree.successor(currNode).key+"");

System.out.println("后继节点是:"+tree.predecessor(currNode).key+"");

drawTree();

//下面这句真心不知道放在哪里好……

//tree.clear();

}

private static void drawTree() {

EventQueue.invokeLater(new Runnable() {

public void run() {

// 创建窗口对象

MyFrame frame = new MyFrame();

// 显示窗口

frame.setVisible(true);

}

});

}

/**

* 窗口

*/

public static class MyFrame extends JFrame {

public static final String TITLE = "红黑树测试";

public static final int HEIGHT = 500;

public static final int WIDTH = (int) (HEIGHT/0.618);

public MyFrame() {

super();

initFrame();

}

private void initFrame() {

// 设置 窗口标题 和 窗口大小

setTitle(TITLE);

setSize(WIDTH, HEIGHT);

// 设置窗口关闭按钮的默认操作(点击关闭时退出进程)

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

// 把窗口位置设置到屏幕的中心

setLocationRelativeTo(null);

// 设置窗口的内容面板

MyPanel panel = new MyPanel(this);

setContentPane(panel);

}

}

/**

* 内容面板

*/

public static class MyPanel extends JPanel {

private MyFrame frame;

//构造

public MyPanel(MyFrame frame) {

super();

this.frame = frame;

}

/**

* 绘制面板的内容: 创建 JPanel 后会调用一次该方法绘制内容,

* 之后如果数据改变需要重新绘制, 可调用 updateUI() 方法触发

* 系统再次调用该方法绘制更新 JPanel 的内容。

*/

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

// 重新调用 Graphics 的绘制方法绘制时将自动擦除旧的内容

/* 自行打开下面注释查看各绘制效果 */

// 1. 线段 折线 drawLine(g);

// 2. 矩形 多边形drawRect(g);

// 3. 圆弧 扇形 drawArc(g);

// 4. 椭圆drawOval(g);

// 5. 图片drawImage(g);

// 6. 文本drawString(g);

((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

((Graphics2D)g).setColor(Color.RED);

((Graphics2D)g).drawLine(0, 25, 1366, 25);

((Graphics2D)g).drawLine(25, 768, 25, 0);

//((Graphics2D)g).drawLine(50, 50, 200, 50);

final Graphics2D g2 = (Graphics2D)g.create();

final float ratio = frame.getWidth()*.8f/(tree.maximum() - tree.minimum());

final float offset = tree.minimum()*ratio-25;

//final float ratioVertival = frame.getHeight()*1.f/(tree.maximum() - tree.minimum());

g2.setFont(new Font(null, Font.ITALIC, 25));

tree.SetInOrderDo(new inOrderDo(){

//mycode

public void dothis(RBTNode n) {

RBTNode n2 = ((RBTNode)n);

if(n2.color==true)

g2.setColor(Color.black);

else g2.setColor(Color.red);

g2.drawString(n2.key+"",n2.key*ratio-offset ,tree.inorderCoounter2*100);

g2.setColor(Color.BLUE);

//draw relationship line

if(n2.parent!=null)

g2.drawLine((int)(n2.key*ratio-offset) ,tree.inorderCoounter2*100, (int)(n2.parent.key*ratio-offset), (tree.inorderCoounter2-1)*100);

}});

tree.inOrderDo();

}

}}

github地址:https://github.com/KnIfER/RBTree-java

……

……

话说天王是何方神圣?

这尊大神是否尚在地球?因为他最近的博客是14年的,名字又那么伤感,不会……吧?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值