mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 15:11:16 +08:00
Add binary search tree.
This commit is contained in:
parent
b89e406444
commit
1c911aadf0
@ -1,17 +1,20 @@
|
||||
export default class BinaryTreeNode {
|
||||
constructor(value = null) {
|
||||
constructor(value = null, parent = null) {
|
||||
this.left = null;
|
||||
this.right = null;
|
||||
this.parent = parent;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
setLeft(node) {
|
||||
this.left = node;
|
||||
this.left.parent = this;
|
||||
return this;
|
||||
}
|
||||
|
||||
setRight(node) {
|
||||
this.right = node;
|
||||
this.right.parent = this;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -23,6 +23,21 @@ describe('BinaryTreeNode', () => {
|
||||
expect(rootNode.right.value).toBe(3);
|
||||
});
|
||||
|
||||
it('should set parent', () => {
|
||||
const leftNode = new BinaryTreeNode(1);
|
||||
const rightNode = new BinaryTreeNode(3);
|
||||
const rootNode = new BinaryTreeNode(2);
|
||||
|
||||
rootNode
|
||||
.setLeft(leftNode)
|
||||
.setRight(rightNode);
|
||||
|
||||
expect(rootNode.parent).toBeNull();
|
||||
expect(rootNode.left.parent.value).toBe(2);
|
||||
expect(rootNode.right.parent.value).toBe(2);
|
||||
expect(rootNode.right.parent).toEqual(rootNode);
|
||||
});
|
||||
|
||||
it('should traverse node', () => {
|
||||
const leftNode = new BinaryTreeNode(1);
|
||||
const rightNode = new BinaryTreeNode(3);
|
||||
|
@ -14,7 +14,7 @@ export default class BinarySearchTree {
|
||||
}
|
||||
|
||||
remove(value) {
|
||||
const nodeToRemove = this.findNode(value);
|
||||
const nodeToRemove = this.root.find(value);
|
||||
|
||||
if (!nodeToRemove) {
|
||||
throw new Error('Item not found in the tree');
|
||||
|
@ -12,14 +12,14 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
|
||||
if (this.left) {
|
||||
this.left.insert(value);
|
||||
} else {
|
||||
this.left = new BinarySearchTreeNode(value);
|
||||
this.setLeft(new BinarySearchTreeNode(value));
|
||||
}
|
||||
} else if (value > this.value) {
|
||||
// Insert to the right.
|
||||
if (this.right) {
|
||||
this.right.insert(value);
|
||||
} else {
|
||||
this.right = new BinarySearchTreeNode(value);
|
||||
this.setRight(new BinarySearchTreeNode(value));
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user