Skip to content

Commit

Permalink
Merge pull request #100 from amejiarosario/fix/nadhem-findings
Browse files Browse the repository at this point in the history
fix(bst): on duplicates values the same node is returned
  • Loading branch information
amejiarosario authored May 24, 2021
2 parents cec3b04 + d350da8 commit 1c05026
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
11 changes: 6 additions & 5 deletions src/data-structures/trees/binary-search-tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,24 @@ class BinarySearchTree {
* @returns {BinaryTreeNode} newly added node
*/
add(value) {
const newNode = new BinaryTreeNode(value);
let node = new BinaryTreeNode(value);

if (this.root) {
const { found, parent } = this.findNodeAndParent(value); // <1>
if (found) { // duplicated: value already exist on the tree
found.meta.multiplicity = (found.meta.multiplicity || 1) + 1; // <2>
node = found;
} else if (value < parent.value) {
parent.setLeftAndUpdateParent(newNode);
parent.setLeftAndUpdateParent(node);
} else {
parent.setRightAndUpdateParent(newNode);
parent.setRightAndUpdateParent(node);
}
} else {
this.root = newNode;
this.root = node;
}

this.size += 1;
return newNode;
return node;
}
// end::add[]

Expand Down
4 changes: 2 additions & 2 deletions src/data-structures/trees/binary-search-tree.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ describe('Binary Search Tree', () => {
it('should deal with duplicates', () => {
const root = bst.add(1);
expect(root.meta.multiplicity).toBe(undefined);
bst.add(1);
expect(bst.add(1)).toBe(root); // should return existing
expect(bst.size).toBe(2);
expect(root.toValues()).toMatchObject({
value: 1, parent: null, left: null, right: null,
Expand Down Expand Up @@ -262,7 +262,7 @@ describe('Binary Search Tree', () => {
});

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

expect(bst.remove(40)).toBe(true);
Expand Down

0 comments on commit 1c05026

Please sign in to comment.