Skip to content

Commit 4466fb4

Browse files
committed
Update insert
1 parent 9a4588a commit 4466fb4

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

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

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,22 @@
4242
}
4343

4444
RBTree.prototype.put = function (key, value) {
45-
return (this._root = this._put(key, value, this._root));
45+
this._root = this._put(key, value, this._root);
46+
this._root.flipColor();
4647
};
4748

4849
RBTree.prototype._put = function (key, value, node) {
4950
var newRoot = node;
5051
if (this._root === null) {
51-
return new Node(key, value, null, null, false);
52+
return new Node(key, value, null, null, true);
5253
}
53-
if (node.getValue() > value) {
54+
if (node.getKey() > key) {
5455
this._put(key, value, node.getLeft());
55-
} else if (node.getValue() < value) {
56-
this._put(key, value, node.getRight());
56+
} else if (node.getKey() < key) {
57+
node.setLeft(this._put(key, value, node.getRight()));
5758
}
5859
if (this._isRed(node.getRight())) {
59-
newRoot = this._rotateLeft(node);
60+
node.setRight(this._rotateLeft(node));
6061
}
6162
if (this._isRed(node.getLeft()) && this._isRed(node.getLeft().getLeft())) {
6263
newRoot = this._rotateRight(node);

test/data-structures/red-black-tree.spec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,13 @@ describe('RBTree', function () {
5353
expect(tree._root.getKey()).toBe('foo');
5454
expect(tree._root.getValue()).toBe('bar');
5555
});
56+
57+
it('should be able to insert a node in 1 level tree', function () {
58+
var tree = new RBTree();
59+
tree.put(1, 'bar');
60+
61+
});
62+
5663
});
64+
5765
});

0 commit comments

Comments
 (0)