045:手写Java红黑树(下-变色左旋转)
1 手写红黑树左旋转代码演示
课程内容:
1.完全纯手写红黑树变换颜色
2.纯手写红黑树左旋转
3.纯手写红黑树变色
4.红黑树查询效率到底有多牛
2 纯手写红黑树左旋转
左旋操作
private void repairTree(Node newNode) {
// 如果父节点为红色,当前节点默认红色,两红相连,变色或者旋转
if (newNode.parent.color.equals(NodeColor.red)) {
// 红黑树变色或者旋转
Node g = newNode.parent.parent;
Node p = newNode.parent;
// 如果如果叔叔节点为黑色或者为空,当前节点在右子树上,左旋+固定旋转的两个节点颜色
if (g.left == null || NodeColor.black.equals(g.left.color) && (g.right == newNode)) {
leftRotate(g);
g.color = NodeColor.red;
p.color = NodeColor.black;
}
}
}
private void leftRotate(Node x) {
// newNode为待翻下的值x,获取待翻上的值y
Node y = x.right;
// x.right原为y,旋转被覆盖掉,用y.left覆盖
x.right = y.left;
if (y.left != null) {
// 待翻上的值y有子节点y.left,更改子节点指向关系
y.left.parent = x;
}
// 父节点改变指向关系
y.parent = x.parent;
// 如果x的parent为空
if (x.parent == null) {
// x为根节点,x翻下y翻上,y变为新根节点
root = y;
} else {
// 否则,判断x为左子树或者右子树,分别做不同的处理
if (x.parent.left == x) {
// x为左子树,父节点的左子树变为y
x.parent.left = y;
} else {
x.parent.right = y;
}
}
// 更改x和y之间的指向关系
y.left = x;
x.parent = y;
}
断点调试:
3 纯手写红黑树变色
变色操作
private void repairTree(Node newNode) {
// 如果父节点为红色,当前节点默认红色,两红相连,变色或者旋转
if (newNode.parent.color.equals(NodeColor.red)) {
// 红黑树变色或者旋转
Node g = newNode.parent.parent;
Node p = newNode.parent;
// 如果叔叔节点和父亲节点都为红,变色操作:将父亲节点+叔叔节点改为黑,爷爷节点改为红
if (g.left != null && NodeColor.red.equals(g.left.color)) {
g.left.color = NodeColor.black;
p.color = NodeColor.black;
g.color = NodeColor.red;
// 根节点一定为黑
if (root == g) {
g.color = NodeColor.black;
}
return;
}
// 如果如果叔叔节点为黑色或者为空,当前节点在右子树上,左旋操作:两个节点旋转+固定旋转的两个节点颜色
if (g.left == null || NodeColor.black.equals(g.left.color) && (g.right == newNode)) {
leftRotate(g);
g.color = NodeColor.red;
p.color = NodeColor.black;
}
}
}
红黑树插入节点4颜色变化步骤图:
断点调试:
4 红黑树查询最大值与最小值
红黑树查询最大值
/**
* 查询最大值
*
* @param node
* @return
*/
public int getMaxValue(Node node) {
if (node != null) {
if (node.right != null) {
return getMaxValue(node.right);
} else {
return node.value;
}
}
return 0;
}
public class Test {
public static void main(String[] args) {
RedBlackTree redBlackTree = new RedBlackTree();
redBlackTree.insert(1);
redBlackTree.insert(2);
redBlackTree.insert(3);
redBlackTree.insert(4);
redBlackTree.insert(5);
int maxValue = redBlackTree.getMaxValue(redBlackTree.root);
System.out.println("maxValue:" + maxValue); //maxValue:5
}
}
红黑树查询时间复杂度o(log n)
如果当前有10亿数字,如何最快的查找到最大/小值?
使用红黑树/平衡二叉树,30次左右,2^30=10亿+