mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2026-03-13 08:51:02 +08:00
Add binary search tree.
This commit is contained in:
@@ -21,20 +21,32 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
|
||||
return this;
|
||||
}
|
||||
|
||||
contains(value) {
|
||||
find(value) {
|
||||
// Check the root.
|
||||
if (this.value === value) {
|
||||
return true;
|
||||
return this;
|
||||
}
|
||||
|
||||
if (value < this.value && this.left) {
|
||||
// Check left nodes.
|
||||
return this.left.contains(value);
|
||||
return this.left.find(value);
|
||||
} else if (value > this.value && this.right) {
|
||||
// Check right nodes.
|
||||
return this.right.contains(value);
|
||||
return this.right.find(value);
|
||||
}
|
||||
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
contains(value) {
|
||||
return !!this.find(value);
|
||||
}
|
||||
|
||||
findMin() {
|
||||
if (!this.left) {
|
||||
return this;
|
||||
}
|
||||
|
||||
return this.left.findMin();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,4 +56,31 @@ describe('BinarySearchTreeNode', () => {
|
||||
expect(bstNode.contains(1)).toBeTruthy();
|
||||
expect(bstNode.contains(3)).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should find min node', () => {
|
||||
const node = new BinarySearchTreeNode(10);
|
||||
|
||||
node.insert(20);
|
||||
node.insert(30);
|
||||
node.insert(5);
|
||||
node.insert(40);
|
||||
node.insert(1);
|
||||
|
||||
expect(node.findMin()).not.toBeNull();
|
||||
expect(node.findMin().value).toBe(1);
|
||||
});
|
||||
|
||||
it('should find node', () => {
|
||||
const node = new BinarySearchTreeNode(10);
|
||||
|
||||
node.insert(20);
|
||||
node.insert(30);
|
||||
node.insert(5);
|
||||
node.insert(40);
|
||||
node.insert(1);
|
||||
|
||||
expect(node.find(6)).toBeNull();
|
||||
expect(node.find(5)).not.toBeNull();
|
||||
expect(node.find(5).value).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user