Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f32e9aa

Browse files
committed
update: BST insertion added
1 parent 31c5648 commit f32e9aa

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

‎src/_DataStructures_/Trees/BST/Node.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = class Node {
2+
constructor(value) {
3+
this.value = value;
4+
this.leftChild = null; // will be a node
5+
this.rightChild = null; // will be a node
6+
}
7+
};

‎src/_DataStructures_/Trees/BST/index.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const Node = require('./Node');
2+
3+
class BinarySearchTree {
4+
constructor(value) {
5+
this.root = new Node(value);
6+
}
7+
8+
insert(root, value) {
9+
if (root === null) {
10+
const newNode = new Node(value);
11+
// eslint-disable-next-line no-param-reassign
12+
root = newNode;
13+
return root;
14+
}
15+
16+
if (value < root.value) {
17+
// go left
18+
// eslint-disable-next-line no-param-reassign
19+
root.leftChild = this.insert(root.leftChild, value);
20+
return root;
21+
}
22+
if (value > root.value) {
23+
// go right
24+
// eslint-disable-next-line no-param-reassign
25+
root.rightChild = this.insert(root.rightChild, value);
26+
return root;
27+
}
28+
return root;
29+
}
30+
}
31+
32+
// const bst = new BinarySearchTree(10);
33+
// console.log(bst.root);
34+
// bst.insert(bst.root, 12);
35+
// bst.insert(bst.root, 9);
36+
// bst.insert(bst.root, 19);
37+
// bst.insert(bst.root, 11);
38+
// bst.insert(bst.root, 6);
39+
40+
// console.log(bst.root);
41+
42+
module.exports = BinarySearchTree;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /