forked from AllAlgorithms/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.js
More file actions
58 lines (55 loc) · 1.61 KB
/
Tree.js
File metadata and controls
58 lines (55 loc) · 1.61 KB
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
// JavaScript implementation of Binary Search
// Author: Youcef Madadi
// Binary Tree
class BinaryTree{
left=null;
right=null;
value;
constructor(value,left,right) {
this.value = value;
if(left instanceof BinaryTree)this.left = left;
if(right instanceof BinaryTree)this.right= right;
}
AddValue(value){
if(value>this.value){
if(this.right) return this.right.AddValue(value);
this.right=new BinaryTree(value)
}else if(value<this.value){
if(this.left) return this.left.AddValue(value);
this.left=new BinaryTree(value)
}else return;
}
Print(){
if(this.left) this.left.Print();
console.log(this.value)
if(this.right) this.right.Print();
}
PrintLRM(){
if(this.left) this.left.Print();
if(this.right) this.right.Print();
console.log(this.value)
}
PrintRML(){
if(this.right) this.right.Print();
console.log(this.value)
if(this.left) this.left.Print();
}
findValue(value){
if( this.value > value ) {
if(this.left)return this.left.findValue(value);
}
else if( this.value < value ) {
if(this.right) return this.right.findValue(value);
}
else return true
return false;
}
static CreateRandomTree(){
let root=new BinaryTree(Math.floor(Math.random() * 100)),
deep= Math.floor(Math.random() * 50);
for( let i=0 ; i<deep; i++){
root.AddValue(Math.floor(Math.random() * 100))
}
return root;
}
}