Repository navigation
Expand file tree
/
Copy pathbinary_search_tree.js
More file actions
111 lines (107 loc) · 3.14 KB
/
Copy pathbinary_search_tree.js
File metadata and controls
111 lines (107 loc) · 3.14 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
let Node = function(data, left = null, right = null) {
this.data = data
this.left = left
this.right = right
}
let BST = function() {
this.root = null;
this.add = function(data) {
const node = this.root
if (node === null) {
this.root = new Node(data);
} else {
const searchtree = function(node) {
if (data < node.data) {
if (node.left === null) {
node.left = new Node(data);
return
} else if (node.left !== null) {
return searchtree(node.left)
}
} else if (data > node.data) {
if (node.right === null) {
node.right = new Node(data)
return
} else if (node.right !== null) {
return searchtree(node.right)
}
} else {
return null
}
}
return searchtree(node)
}
}
this.min = function() {
const node = this.root
let bs = function(node) {
if (node.left == null) {
return node.data
}
if (node.left != null) {
bs(node.left)
}
}
return bs(node)
}
this.max = function() {
const current = this.root
let bs = function(current) {
if (current.right == null) {
return current.data
}
if (current.right != null) {
bs(current.right)
}
}
return bs(current)
}
this.isPresent = function(value) {
let thiscurrent = this.root
let isFound = function(data, current) {
let ispresent = false
if (!(current.data == data)) {
if (data < current.data) {
current = current.left
} else {
current = current.right
}
isFound(data, current)
} else {
ispresent = true
}
return ispresent
}
return isFound(value, thiscurrent)
}
this.remove = function(value) {
let node = this.root
let deleterecur = function(node) {
if (node.left == null && node.right == null) {
node = null;
} else if (node.left == null) {
deleterecur(node.right)
} else if (node.right == null) {
deleterecur(node.left)
} else {
deleterecur(node.left)
deleterecur(node.right)
}
}
let search = function(value) {
if (value > node.data) {
search(node.right)
} else if (value < node.data) {
search(node.left)
} else if (value == node.data) {
deleterecur(node)
}
}
}
}
let bst = new BST;
bst.add(5)
bst.add(1)
console.log(bst.isPresent(5))
console.log(bst.isPresent(7))
console.log(bst.isPresent(1))