Skip to content

Commit 73ecf25

Browse files
marrcelomgechev
authored andcommitted
Fix AVLTree remove (mgechev#139) (mgechev#165)
1 parent 37b0643 commit 73ecf25

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/data-structures/avl-tree.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,7 @@
110110
// y should be child of z with larger height
111111
// (cannot be ancestor of removed node)
112112
var y;
113-
if (z._left !== null && z._right !== null){
114-
y = (z._left === y) ? z._right : z._left;
115-
} else if (z._left !== null && z._right === null){
113+
if ((z._left !== null && z._right !== null) || (z._left !== null && z._right === null)){
116114
y = z._left;
117115
} else if (z._right !== null && z._left === null){
118116
y = z._right;
@@ -602,7 +600,7 @@
602600
var temp = node.value;
603601
node.value = min.value;
604602
min.value = temp;
605-
return this.remove(min);
603+
return this.remove(temp);
606604
} else {
607605
if (node._left) {
608606
this._replaceChild(node._parent, node, node._left);

test/data-structures/avl-tree.spec.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,4 +163,31 @@ describe('AVL Tree', function () {
163163
expect(avlTree._root._right.value).toBe(25);
164164
expect(avlTree._root._right._height).toBe(1);
165165
});
166+
it('should remove nodes and balance properly (3)', function () {
167+
var avlTree = new AVLTree();
168+
avlTree.insert(55);
169+
avlTree.insert(25);
170+
avlTree.insert(11);
171+
avlTree.insert(1);
172+
avlTree.remove(55);
173+
avlTree.insert(32);
174+
avlTree.insert(37);
175+
avlTree.insert(41);
176+
avlTree.insert(8);
177+
avlTree.insert(44);
178+
avlTree.insert(6);
179+
avlTree.remove(32);
180+
avlTree.remove(11);
181+
avlTree.remove(25);
182+
183+
// depth 1
184+
expect(avlTree._root.value).toBe(37);
185+
expect(avlTree._root._height).toBe(4);
186+
// depth 2
187+
expect(avlTree._root._left.value).toBe(6);
188+
expect(avlTree._root._left._height).toBe(3);
189+
190+
expect(avlTree._root._right.value).toBe(41);
191+
expect(avlTree._root._right._height).toBe(2);
192+
});
166193
});

0 commit comments

Comments
 (0)