mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +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;
|
||||
}
|
||||
|
||||
addLeft(node) {
|
||||
setLeft(node) {
|
||||
this.left = node;
|
||||
return this;
|
||||
}
|
||||
|
||||
addRight(node) {
|
||||
setRight(node) {
|
||||
this.right = node;
|
||||
return this;
|
||||
}
|
||||
|
@ -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]);
|
||||
|
||||
|
@ -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) {
|
||||
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user