红黑树的介绍
红黑树是一种平衡二叉树。这种树可以进行高效的中序遍历。通过对任何一条从根到叶子的简单路径上各个节点的颜色进行约束,确保没有一条路径会比其他路径长2倍,因而是近似平衡的。所以相对于严格要求平衡的AVL树来说,它的旋转保持平衡次数较少。用于搜索时,插入删除次数多的情况下我们就用红黑树来取代AVL。广泛用在C++的STL中。如map和set都是用红黑树实现的。
ES6红黑树完整实现代码:
let RedBlackTree = (function() {
let Colors = {
RED: 0,
BLACK: 1
};
class Node {
constructor(key, color) {
this.key = key;
this.left = null;
this.right = null;
this.color = color;
this.flipColor = function() {
if(this.color === Colors.RED) {
this.color = Colors.BLACK;
} else {
this.color = Colors.RED;
}
};
}
}
class RedBlackTree {
constructor() {
this.root = null;
}
getRoot() {
return this.root;
}
isRed(node) {
if(!node) {
return false;
}
return node.color === Colors.RED;
}
flipColors(node) {
node.left.flipColor();
node.right.flipColor();
}
rotateLeft(node) {
var temp = node.right;
if(temp !== null) {
node.right = temp.left;
temp.left = node;
temp.color = node.color;
node.color = Colors.RED;
}
return temp;
}
rotateRight(node) {
var temp = node.left;
if(temp !== null) {
node.left = temp.right;
temp.right = node;
temp.color = node.color;
node.color = Colors.RED;
}
return temp;
}
insertNode(node, element) {
if(node === null) {
return new Node(element, Colors.RED);
}
var newRoot = node;
if(element < node.key) {
node.left = this.insertNode(node.left, element);
} else if(element > node.key) {
node.right =this.insertNode(node.right, element);
} else {
node.key = element;
}
if(this.isRed(node.right) && !this.isRed(node.left)) {
newRoot = this.rotateLeft(node);
}
if(this.isRed(node.left) && this.isRed(node.left.left)) {
newRoot = this.rotateRight(node);
}
if(this.isRed(node.left) && this.isRed(node.right)) {
this.flipColors(node);
}
return newRoot;
}
insert(element) {
this.root = insertNode(this.root, element);
this.root.color = Colors.BLACK;
}
}
return RedBlackTree;
})()
用法实例
var rbTree = new RedBlackTree();
rbTree.insert(1);
rbTree.insert(2);
rbTree.insert(3);
rbTree.insert(4);
rbTree.insert(5);
rbTree.insert(6);
rbTree.insert(7);
rbTree.insert(14);
rbTree.insert(15);
rbTree.insert(13);
rbTree.insert(12);
rbTree.insert(11);
rbTree.getRoot();
相关文章
javascript 二叉树(Trees)算法与说明:http://blog.csdn.net/rth362147773/article/details/77996814
javascript AVL树算法与说明:http://blog.csdn.net/rth362147773/article/details/78014586