Skip to content

Commit 0fd390c

Browse files
author
chenweijie
committed
红黑树
1 parent 76ee6f6 commit 0fd390c

File tree

1 file changed

+113
-0
lines changed
  • src/main/java/com/chen/algorithm/tree/rbtree

1 file changed

+113
-0
lines changed
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package com.chen.algorithm.tree.rbtree;
2+
3+
/**
4+
* 红黑树节点类
5+
* <p>
6+
* 节点类和二叉树的节点类差不多,只不过在其基础上增加了一个 boolean 类型的变量来表示节点的颜色
7+
*
8+
* @author : chen weijie
9+
* @Date: 2019-04-10 12:18 AM
10+
*/
11+
public class RBNode<T extends Comparable<T>> {
12+
13+
/**
14+
* 颜色
15+
*/
16+
boolean color;
17+
18+
/**
19+
* 关键值
20+
*/
21+
T key;
22+
23+
/**
24+
* 左子节点
25+
*/
26+
RBNode<T> left;
27+
28+
/**
29+
* 右子节点
30+
*/
31+
RBNode<T> right;
32+
33+
/**
34+
* 父节点
35+
*/
36+
RBNode<T> parent;
37+
38+
39+
public RBNode(boolean color, T key, RBNode<T> left, RBNode<T> right, RBNode<T> parent) {
40+
this.color = color;
41+
this.key = key;
42+
this.left = left;
43+
this.right = right;
44+
this.parent = parent;
45+
}
46+
47+
48+
/**
49+
* 获取节点的关键值
50+
*
51+
* @return
52+
*/
53+
public T getKey() {
54+
return key;
55+
}
56+
57+
/**
58+
* 打印节点的关键值和颜色信息
59+
*/
60+
@Override
61+
public String toString() {
62+
return "" + key + (this.color ? "R" : "B");
63+
}
64+
65+
66+
/*************对红黑树节点x进行左旋操作 ******************/
67+
68+
/***
69+
*
70+
* 左旋示意图:对节点x进行左旋
71+
* p p
72+
* / /
73+
* x y
74+
* / \ / \
75+
* lx y -----> x ry
76+
* / \ / \
77+
* ly ry lx ly
78+
*
79+
* 左旋做了三件事:
80+
* 1. 将y的左子节点赋给x的右子节点,并将x赋给y左子节点的父节点(y左子节点非空时)
81+
* 2. 将x的父节点p(非空时)赋给y的父节点,同时更新p的子节点为y(左或右)
82+
* 3. 将y的左子节点设为x,将x的父节点设为y
83+
*/
84+
private void leftRotate(RBNode<T> x){
85+
86+
87+
88+
}
89+
90+
91+
/*************对红黑树节点y进行右旋操作 ******************/
92+
/**
93+
*
94+
* 左旋示意图:对节点y进行右旋
95+
* p p
96+
* / /
97+
* y x
98+
* / \ / \
99+
* x ry -----> lx y
100+
* / \ / \
101+
* lx rx rx ry
102+
* 右旋做了三件事:
103+
* 1. 将x的右子节点赋给y的左子节点,并将y赋给x右子节点的父节点(x右子节点非空时)
104+
* 2. 将y的父节点p(非空时)赋给x的父节点,同时更新p的子节点为x(左或右)
105+
* 3. 将x的右子节点设为y,将y的父节点设为x
106+
*/
107+
private void rightRotate(RBNode<T> y){
108+
109+
}
110+
111+
112+
113+
}

0 commit comments

Comments
 (0)