Skip to content

Commit 5d6c596

Browse files
authored
Create Tree.js
1 parent 1275895 commit 5d6c596

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

03-DataStructures/Tree.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class TreeNode {
2+
constructor(value) {
3+
this.value = value;
4+
this.left = null;
5+
this.right = null;
6+
}
7+
}
8+
9+
class BinarySearchTree {
10+
constructor() {
11+
this.root = null;
12+
}
13+
14+
// Insert a value into the tree
15+
insert(value) {
16+
const newNode = new TreeNode(value);
17+
18+
if (!this.root) {
19+
this.root = newNode;
20+
} else {
21+
this._insertNode(this.root, newNode);
22+
}
23+
}
24+
25+
_insertNode(node, newNode) {
26+
if (newNode.value < node.value) {
27+
if (!node.left) {
28+
node.left = newNode;
29+
} else {
30+
this._insertNode(node.left, newNode);
31+
}
32+
} else {
33+
if (!node.right) {
34+
node.right = newNode;
35+
} else {
36+
this._insertNode(node.right, newNode);
37+
}
38+
}
39+
}
40+
41+
// Other tree operations (search, remove, etc.) can be added here
42+
}
43+
44+
// Example usage:
45+
const bst = new BinarySearchTree();
46+
bst.insert(10);
47+
bst.insert(5);
48+
bst.insert(15);
49+
bst.insert(3);
50+
bst.insert(7);
51+

0 commit comments

Comments
 (0)