Add binary search tree.

This commit is contained in:
Oleksii Trekhleb 2018-04-03 07:50:30 +03:00
parent b89e406444
commit 1c911aadf0
4 changed files with 22 additions and 4 deletions

View File

@ -1,17 +1,20 @@
export default class BinaryTreeNode { export default class BinaryTreeNode {
constructor(value = null) { constructor(value = null, parent = null) {
this.left = null; this.left = null;
this.right = null; this.right = null;
this.parent = parent;
this.value = value; this.value = value;
} }
setLeft(node) { setLeft(node) {
this.left = node; this.left = node;
this.left.parent = this;
return this; return this;
} }
setRight(node) { setRight(node) {
this.right = node; this.right = node;
this.right.parent = this;
return this; return this;
} }

View File

@ -23,6 +23,21 @@ describe('BinaryTreeNode', () => {
expect(rootNode.right.value).toBe(3); 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', () => { it('should traverse node', () => {
const leftNode = new BinaryTreeNode(1); const leftNode = new BinaryTreeNode(1);
const rightNode = new BinaryTreeNode(3); const rightNode = new BinaryTreeNode(3);

View File

@ -14,7 +14,7 @@ export default class BinarySearchTree {
} }
remove(value) { remove(value) {
const nodeToRemove = this.findNode(value); const nodeToRemove = this.root.find(value);
if (!nodeToRemove) { if (!nodeToRemove) {
throw new Error('Item not found in the tree'); throw new Error('Item not found in the tree');

View File

@ -12,14 +12,14 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
if (this.left) { if (this.left) {
this.left.insert(value); this.left.insert(value);
} else { } else {
this.left = new BinarySearchTreeNode(value); this.setLeft(new BinarySearchTreeNode(value));
} }
} else if (value > this.value) { } 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);
} else { } else {
this.right = new BinarySearchTreeNode(value); this.setRight(new BinarySearchTreeNode(value));
} }
} }