diff --git a/src/data-structures/tree/BinaryTreeNode.js b/src/data-structures/tree/BinaryTreeNode.js index fed5b7c2..c4edba28 100644 --- a/src/data-structures/tree/BinaryTreeNode.js +++ b/src/data-structures/tree/BinaryTreeNode.js @@ -5,12 +5,12 @@ export default class BinaryTreeNode { this.value = value; } - addLeft(node) { + setLeft(node) { this.left = node; return this; } - addRight(node) { + setRight(node) { this.right = node; return this; } diff --git a/src/data-structures/tree/__test__/BinaryTreeNode.test.js b/src/data-structures/tree/__test__/BinaryTreeNode.test.js index 8f500860..65ec5977 100644 --- a/src/data-structures/tree/__test__/BinaryTreeNode.test.js +++ b/src/data-structures/tree/__test__/BinaryTreeNode.test.js @@ -15,8 +15,8 @@ describe('BinaryTreeNode', () => { const rootNode = new BinaryTreeNode(2); rootNode - .addLeft(leftNode) - .addRight(rightNode); + .setLeft(leftNode) + .setRight(rightNode); expect(rootNode.value).toBe(2); expect(rootNode.left.value).toBe(1); @@ -29,8 +29,8 @@ describe('BinaryTreeNode', () => { const rootNode = new BinaryTreeNode(2); rootNode - .addLeft(leftNode) - .addRight(rightNode); + .setLeft(leftNode) + .setRight(rightNode); expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]); diff --git a/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js b/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js index 6fb7db69..584ac182 100644 --- a/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js +++ b/src/data-structures/tree/binary-search-tree/BinarySearchTreeNode.js @@ -2,6 +2,11 @@ import BinaryTreeNode from '../BinaryTreeNode'; export default class BinarySearchTreeNode extends BinaryTreeNode { insert(value) { + if (this.value === null) { + this.value = value; + return this; + } + if (value < this.value) { // Insert to the left. if (this.left) { diff --git a/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js b/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js index 0fb88539..306a6fbf 100644 --- a/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js +++ b/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTreeNode.test.js @@ -9,6 +9,15 @@ describe('BinarySearchTreeNode', () => { expect(bstNode.right).toBeNull(); }); + it('should insert in itself if it is empty', () => { + const bstNode = new BinarySearchTreeNode(); + bstNode.insert(1); + + expect(bstNode.value).toBe(1); + expect(bstNode.left).toBeNull(); + expect(bstNode.right).toBeNull(); + }); + it('should insert nodes in correct order', () => { const bstNode = new BinarySearchTreeNode(2); bstNode.insert(1);