Skip to content

Commit fc6c804

Browse files
committed
Changes in the insertion algorithm
1 parent eca6d26 commit fc6c804

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/data-structures/red-black-tree.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
return !!this._isRed;
1515
};
1616

17+
Node.prototype.flipColor = function () {
18+
this._isRed = !this._isRed;
19+
};
20+
1721
'key value left right'
1822
.split(' ')
1923
.forEach(function (key) {
@@ -42,9 +46,30 @@
4246
};
4347

4448
RBTree.prototype._put = function (key, value, node) {
49+
var newRoot = node;
4550
if (this._root === null) {
46-
return (this._root = new Node(key, null, null, value, false));
51+
return new Node(key, null, null, value, false);
52+
}
53+
if (node.getValue() > value) {
54+
this._put(key, value, node.getLeft());
55+
} else if (node.getValue() < value) {
56+
this._put(key, value, node.getRight());
57+
}
58+
if (this._isRed(node.getRight())) {
59+
newRoot = this._rotateLeft(node);
4760
}
61+
if (this._isRed(node.getLeft()) && this._isRed(node.getLeft().getLeft())) {
62+
newRoot = this._rotateRight(node);
63+
}
64+
if (this._isRed(node.getLeft()) && this._isRed(node.getRight())) {
65+
this._flipColors();
66+
}
67+
return newRoot;
68+
};
69+
70+
RBTree.prototype._flipColors = function (node) {
71+
node.getLeft().flipColor();
72+
node.getRight().flipColor();
4873
};
4974

5075
RBTree.prototype._rotateLeft = function (node) {

0 commit comments

Comments
 (0)