超详细超清楚的红黑树解析
2-3查找树
插入原理图
红黑二叉查找树
与2-3查找树的联系
将树中的链接分为两种类型,红链接将两个2-结点连接起来构成一个3-结点,黑色则是普通链接。
定义:
1. 红链接均为左链接
2. 没有任何一个结点同时和两条红链接相连
3. 该树是完美黑色平衡的,即任意空链接到根节点的路径上的黑链接数量相同。
该定义与的红黑树与相应的2-3树为一一对应
**根结点总是黑色的
- 左旋和右旋
function rotateLeft (node) {
let x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = RED;
x.N = node.N;
node.N = 1 + size(node.left) + size(node.right);
return x;
}
function rotateRight (node) {
let x = node.left;
x.left = node.right;
x.right = node;
x.color = node.color;
node.color = RED;
x.N = node.N;
h.N = 1 + size(node.right) + size(node.left);
}
const RED = true;
const BLACK = false;
class Node {
constructor (key, value) {
this.key = key;
this.value = value;
this.N = 1;
this.color = RED;//其父结点指向他的链接的颜色,红色为true,黑色为false;
this.left = null;
this.right = null;
}
}
class RedBlackBST {
constructor () {
this.root = null;
}
isRed (node) {
return node && node.color || false;
}
put (node, key, value) {
if (arguments.length === 2) {
return this.put(this.root, key, value);
}
if(node === null){
let x = new Node(key, value);
return x;
}
let cmp = compare(key, node.key);
if (cmp > 0) {
node.left = this.put(node.left, key, value);
} else if (cmp < 0) {
node.right = this.put (node.right, key, value);
} else {
node.value = value;
}
if(this.isRed(node.left) && this.isRed(node.right)) {
this.flipColors(node);
return node;
}
if(this.isRed(node.left) && this.isRed(node.left.left)){
let x = this.rotateRight
}
}
}
RedBlackBST.prototype.rotateLeft = rotateLeft;
RedBlackBST.prototype.rotaterRight = rotateRight;
RedBlackBST.prototype.flipColors = flipColors;
RedBlackBST.prototype.size = size;
function rotateLeft (node) {
let x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = RED;
x.N = node.N;
node.N = 1 + this.size(node.left) + this.size(node.right);
return x;
}
function rotateRight (node) {
let x = node.left;
x.left = node.right;
x.right = node;
x.color = node.color;
node.color = RED;
x.N = node.N;
h.N = 1 + this.size(node.right) + this.size(node.left);
return x;
}
function flipColors (node) {
node.left.color = BLACK;
node.right.color = BLACK;
node.color = RED;
}
function size (node) {
return node ? node.N : 0;
}
function compare (key1, key2){
if (key1 < key2) {
return 1;
}
if (key1 === key2) {
return 0;
}
if (key1 > key2) {
return -1;
}
}