mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 23:21:18 +08:00
Add binary search tree.
This commit is contained in:
parent
8caf3a2201
commit
873024079a
@ -9,7 +9,7 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
|
|||||||
} else {
|
} else {
|
||||||
this.left = new BinarySearchTreeNode(value);
|
this.left = new BinarySearchTreeNode(value);
|
||||||
}
|
}
|
||||||
} else {
|
} else if (value > this.value) {
|
||||||
// Insert to the right.
|
// Insert to the right.
|
||||||
if (this.right) {
|
if (this.right) {
|
||||||
this.right.insert(value);
|
this.right.insert(value);
|
||||||
@ -30,7 +30,7 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
|
|||||||
if (value < this.value && this.left) {
|
if (value < this.value && this.left) {
|
||||||
// Check left nodes.
|
// Check left nodes.
|
||||||
return this.left.contains(value);
|
return this.left.contains(value);
|
||||||
} else if (this.right) {
|
} else if (value > this.value && this.right) {
|
||||||
// Check right nodes.
|
// Check right nodes.
|
||||||
return this.right.contains(value);
|
return this.right.contains(value);
|
||||||
}
|
}
|
||||||
|
@ -41,4 +41,19 @@ describe('BinarySearchTreeNode', () => {
|
|||||||
expect(bstNode.contains(6)).toBeTruthy();
|
expect(bstNode.contains(6)).toBeTruthy();
|
||||||
expect(bstNode.contains(8)).toBeFalsy();
|
expect(bstNode.contains(8)).toBeFalsy();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should not insert duplicates', () => {
|
||||||
|
const bstNode = new BinarySearchTreeNode(2);
|
||||||
|
bstNode.insert(1);
|
||||||
|
|
||||||
|
expect(bstNode.toString()).toBe('1,2');
|
||||||
|
expect(bstNode.contains(1)).toBeTruthy();
|
||||||
|
expect(bstNode.contains(3)).toBeFalsy();
|
||||||
|
|
||||||
|
bstNode.insert(1);
|
||||||
|
|
||||||
|
expect(bstNode.toString()).toBe('1,2');
|
||||||
|
expect(bstNode.contains(1)).toBeTruthy();
|
||||||
|
expect(bstNode.contains(3)).toBeFalsy();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user