Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1c05026

Browse files
Merge pull request #100 from amejiarosario/fix/nadhem-findings
fix(bst): on duplicates values the same node is returned
2 parents cec3b04 + d350da8 commit 1c05026

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

‎src/data-structures/trees/binary-search-tree.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,24 @@ class BinarySearchTree {
1919
* @returns {BinaryTreeNode} newly added node
2020
*/
2121
add(value) {
22-
constnewNode = new BinaryTreeNode(value);
22+
letnode = new BinaryTreeNode(value);
2323

2424
if (this.root) {
2525
const { found, parent } = this.findNodeAndParent(value); // <1>
2626
if (found) { // duplicated: value already exist on the tree
2727
found.meta.multiplicity = (found.meta.multiplicity || 1) + 1; // <2>
28+
node = found;
2829
} else if (value < parent.value) {
29-
parent.setLeftAndUpdateParent(newNode);
30+
parent.setLeftAndUpdateParent(node);
3031
} else {
31-
parent.setRightAndUpdateParent(newNode);
32+
parent.setRightAndUpdateParent(node);
3233
}
3334
} else {
34-
this.root = newNode;
35+
this.root = node;
3536
}
3637

3738
this.size += 1;
38-
return newNode;
39+
return node;
3940
}
4041
// end::add[]
4142

‎src/data-structures/trees/binary-search-tree.spec.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ describe('Binary Search Tree', () => {
6666
it('should deal with duplicates', () => {
6767
const root = bst.add(1);
6868
expect(root.meta.multiplicity).toBe(undefined);
69-
bst.add(1);
69+
expect(bst.add(1)).toBe(root);// should return existing
7070
expect(bst.size).toBe(2);
7171
expect(root.toValues()).toMatchObject({
7272
value: 1, parent: null, left: null, right: null,
@@ -262,7 +262,7 @@ describe('Binary Search Tree', () => {
262262
});
263263

264264
it('should remove duplicates', () => {
265-
bst.add(40); // add duplicate
265+
expect(bst.add(40)).toBe(n40); // add duplicate
266266
expect(n40.meta.multiplicity).toBe(2);
267267

268268
expect(bst.remove(40)).toBe(true);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /