mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-14 06:52:59 +08:00
Add binary search tree.
This commit is contained in:
parent
ff2df770b8
commit
c5bccffe36
@ -5,12 +5,12 @@ export default class BinaryTreeNode {
|
|||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
addLeft(node) {
|
setLeft(node) {
|
||||||
this.left = node;
|
this.left = node;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
addRight(node) {
|
setRight(node) {
|
||||||
this.right = node;
|
this.right = node;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
@ -15,8 +15,8 @@ describe('BinaryTreeNode', () => {
|
|||||||
const rootNode = new BinaryTreeNode(2);
|
const rootNode = new BinaryTreeNode(2);
|
||||||
|
|
||||||
rootNode
|
rootNode
|
||||||
.addLeft(leftNode)
|
.setLeft(leftNode)
|
||||||
.addRight(rightNode);
|
.setRight(rightNode);
|
||||||
|
|
||||||
expect(rootNode.value).toBe(2);
|
expect(rootNode.value).toBe(2);
|
||||||
expect(rootNode.left.value).toBe(1);
|
expect(rootNode.left.value).toBe(1);
|
||||||
@ -29,8 +29,8 @@ describe('BinaryTreeNode', () => {
|
|||||||
const rootNode = new BinaryTreeNode(2);
|
const rootNode = new BinaryTreeNode(2);
|
||||||
|
|
||||||
rootNode
|
rootNode
|
||||||
.addLeft(leftNode)
|
.setLeft(leftNode)
|
||||||
.addRight(rightNode);
|
.setRight(rightNode);
|
||||||
|
|
||||||
expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]);
|
expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]);
|
||||||
|
|
||||||
|
@ -2,6 +2,11 @@ import BinaryTreeNode from '../BinaryTreeNode';
|
|||||||
|
|
||||||
export default class BinarySearchTreeNode extends BinaryTreeNode {
|
export default class BinarySearchTreeNode extends BinaryTreeNode {
|
||||||
insert(value) {
|
insert(value) {
|
||||||
|
if (this.value === null) {
|
||||||
|
this.value = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
if (value < this.value) {
|
if (value < this.value) {
|
||||||
// Insert to the left.
|
// Insert to the left.
|
||||||
if (this.left) {
|
if (this.left) {
|
||||||
|
@ -9,6 +9,15 @@ describe('BinarySearchTreeNode', () => {
|
|||||||
expect(bstNode.right).toBeNull();
|
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', () => {
|
it('should insert nodes in correct order', () => {
|
||||||
const bstNode = new BinarySearchTreeNode(2);
|
const bstNode = new BinarySearchTreeNode(2);
|
||||||
bstNode.insert(1);
|
bstNode.insert(1);
|
||||||
|
Loading…
Reference in New Issue
Block a user