Skip to content

Commit 1c911aa

Browse files
committedApr 3, 2018
Add binary search tree.
1 parent b89e406 commit 1c911aa

File tree

4 files changed

+22
-4
lines changed

4 files changed

+22
-4
lines changed
 

‎src/data-structures/tree/BinaryTreeNode.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
export default class BinaryTreeNode {
2-
constructor(value = null) {
2+
constructor(value = null, parent = null) {
33
this.left = null;
44
this.right = null;
5+
this.parent = parent;
56
this.value = value;
67
}
78

89
setLeft(node) {
910
this.left = node;
11+
this.left.parent = this;
1012
return this;
1113
}
1214

1315
setRight(node) {
1416
this.right = node;
17+
this.right.parent = this;
1518
return this;
1619
}
1720

‎src/data-structures/tree/__test__/BinaryTreeNode.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,21 @@ describe('BinaryTreeNode', () => {
2323
expect(rootNode.right.value).toBe(3);
2424
});
2525

26+
it('should set parent', () => {
27+
const leftNode = new BinaryTreeNode(1);
28+
const rightNode = new BinaryTreeNode(3);
29+
const rootNode = new BinaryTreeNode(2);
30+
31+
rootNode
32+
.setLeft(leftNode)
33+
.setRight(rightNode);
34+
35+
expect(rootNode.parent).toBeNull();
36+
expect(rootNode.left.parent.value).toBe(2);
37+
expect(rootNode.right.parent.value).toBe(2);
38+
expect(rootNode.right.parent).toEqual(rootNode);
39+
});
40+
2641
it('should traverse node', () => {
2742
const leftNode = new BinaryTreeNode(1);
2843
const rightNode = new BinaryTreeNode(3);

‎src/data-structures/tree/binary-search-tree/BinarySearchTree.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export default class BinarySearchTree {
1414
}
1515

1616
remove(value) {
17-
const nodeToRemove = this.findNode(value);
17+
const nodeToRemove = this.root.find(value);
1818

1919
if (!nodeToRemove) {
2020
throw new Error('Item not found in the tree');

‎src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
1212
if (this.left) {
1313
this.left.insert(value);
1414
} else {
15-
this.left = new BinarySearchTreeNode(value);
15+
this.setLeft(new BinarySearchTreeNode(value));
1616
}
1717
} else if (value > this.value) {
1818
// Insert to the right.
1919
if (this.right) {
2020
this.right.insert(value);
2121
} else {
22-
this.right = new BinarySearchTreeNode(value);
22+
this.setRight(new BinarySearchTreeNode(value));
2323
}
2424
}
2525

0 commit comments

Comments
 (0)
Please sign in to comment.