forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search_Tree.js
98 lines (94 loc) · 1.78 KB
/
Binary_Search_Tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class node
{
constructor(value)
{
this.value=value;
this.left=null;
this.right=null;
}
}
class myBST
{
constructor()
{
this.root=null;
}
insert(value) //inserting a child/parent node
{
const newNode=new node(value);
if(this.root===null)
{
this.root=newNode;
}
else
{
let currentNode=this.root;
while(true)
{
if(value<currentNode.value)
{
if(!currentNode.left)
{
currentNode.left=newNode;
return this;
}
currentNode=currentNode.left;
}
else
{
if(!currentNode.right)
{
currentNode.right=newnode;
return this;
}
currentNode=currentNode.right;
}
}
}
}
lookup(value) //the lookup function
{
if(!this.root)
{
return false;
}
let currentnode=this.root;
while(currentnode)
{
if(value<currentnode.value)
{
currentnode=currentnode.left;
}
else if(value>currentnode.value)
{
currentnode=currentnode.right;
}
else if(currentnode.value===value)
{
return currentnode;
}
}
return null;
}
}
const tree=new myBST();
tree.insert(10);
tree.insert(9);
tree.insert(7);
tree.lookup(10);
//JSON.stringify(traverse(tree.root));
function traverse(node) {
const tree = { value: node.value };
tree.left = node.left === null ? null : traverse(node.left);
tree.right = node.right === null ? null : traverse(node.right);
return tree;
}
// OUTPUT =>
// node {
// value: 10,
// left:
// node {
// value: 9,
// left: node { value: 7, left: null, right: null },
// right: null },
// right: null }