-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbstValidateNode.js
90 lines (73 loc) · 1.71 KB
/
bstValidateNode.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
class node{
constructor(value){
this.value=value
this.left=null
this.right=null
}
}
class binaryTree{
constructor(){
this.root=null
}
insert(value){
let newNode=new node(value)
if(!this.root){
this.root=newNode
return
}
let current=this.root
while(true){
if(value===current.value){
return
}
if(value<current.value){
if(!current.left){
current.left=newNode
return
}current=current.left
}if(value>current.value){
if(!current.right){
current.right=newNode
return
}current=current.right
}
}
}
min(current){
if(current.left==null){
return current.value
}else{
return this.min(current.left)
}
}
max(current){
if(current.right==null){
return current.value
}else{
this.max(current.right)
}
}
validate(current){
if(current==null){
return true
}
if(current.left !=null && this.max(current.left)>current.data){
return false
}
if(current.right!=null && this.min(current.right)<current.data){
return false
}
if(!this.validate(current.left)||this.validate(current.right)){
return false
}
return true
}
}
let bt=new binaryTree
bt.insert(4)
bt.insert(2)
bt.insert(5)
bt.insert(1)
bt.insert(3)
console.log(bt.validate(bt.root));
console.log(bt.root);