Skip to content

Commit d350da8

Browse files
committed
fix(bst): on duplicates values the same node is returned
Fixesamejiarosario#99
1 parent cec3b04 commit d350da8

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

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

+6-5
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=newBinaryTreeNode(value);
22+
letnode=newBinaryTreeNode(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
}elseif(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-
returnnewNode;
39+
returnnode;
3940
}
4041
// end::add[]
4142

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ describe('Binary Search Tree', () => {
6666
it('should deal with duplicates',()=>{
6767
constroot=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)
close