Skip to content

Commit 1dc9555

Browse files
author
Mohit Sharma
authored
Added Implementation of BST
1 parent 6a1344d commit 1dc9555

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

Data Structures/Tree/bst.js

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/*Binary Search Tree!!
2+
*
3+
* Nodes that will go on the Binary Tree.
4+
* They consist of the data in them, the node to the left, the node
5+
* to the right, and the parent from which they came from.
6+
*
7+
* A binary tree is a data structure in which an element
8+
* has two successors(children). The left child is usually
9+
* smaller than the parent, and the right child is usually
10+
* bigger.
11+
*/
12+
13+
// Node in the tree
14+
function Node(val) {
15+
this.value = val;
16+
this.left = null;
17+
this.right = null;
18+
}
19+
20+
// Search the tree for a value
21+
Node.prototype.search = function(val) {
22+
if (this.value == val) {
23+
return this;
24+
} else if (val < this.value && this.left != null) {
25+
return this.left.search(val);
26+
} else if (val > this.value && this.right != null) {
27+
return this.right.search(val);
28+
}
29+
return null;
30+
}
31+
32+
// Visit a node
33+
Node.prototype.visit = function() {
34+
// Recursively go left
35+
if (this.left != null) {
36+
this.left.visit();
37+
}
38+
// Print out value
39+
console.log(this.value);
40+
// Recursively go right
41+
if (this.right != null) {
42+
this.right.visit();
43+
}
44+
}
45+
46+
// Add a node
47+
Node.prototype.addNode = function(n) {
48+
if (n.value < this.value) {
49+
if (this.left == null) {
50+
this.left = n;
51+
} else {
52+
this.left.addNode(n)
53+
}
54+
} else if (n.value > this.value) {
55+
if (this.right == null) {
56+
this.right = n;
57+
} else {
58+
this.right.addNode(n);
59+
}
60+
}
61+
}
62+
63+
function Tree() {
64+
// Just store the root
65+
this.root = null;
66+
}
67+
68+
// Inorder traversal
69+
Tree.prototype.traverse = function() {
70+
this.root.visit();
71+
}
72+
73+
// Start by searching the root
74+
Tree.prototype.search = function(val) {
75+
var found = this.root.search(val);
76+
console.log("Found:"+found.value);
77+
}
78+
79+
// Add a new value to the tree
80+
Tree.prototype.addValue = function(val) {
81+
var n = new Node(val);
82+
if (this.root == null) {
83+
this.root = n;
84+
} else {
85+
this.root.addNode(n);
86+
}
87+
}
88+
89+
//Implementation of BST
90+
var bst = new Tree();
91+
bst.addValue(6);
92+
bst.addValue(3);
93+
bst.addValue(9);
94+
bst.addValue(2);
95+
bst.addValue(8);
96+
bst.addValue(4);
97+
bst.traverse();
98+
bst.search(8);

0 commit comments

Comments
 (0)