-
Notifications
You must be signed in to change notification settings - Fork 0
/
bstRemoveNode.js
105 lines (83 loc) · 2.12 KB
/
bstRemoveNode.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
99
100
101
102
103
104
105
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
}else{
let current=this.root
while(true){
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
}
}
}
}
remove(value){
this.root=this.removeNode(this.root,value)
}
removeNode(current,value){
if(current===null){
return current
}
if(value<current.value){
current.left=this.removeNode(current.left,value)
}else if(value>current.value){
current.right=this.removeNode(current.right,value)
}
else{
if(!current.left&&!current.right){
return null
}
if(!current.left){
return current.right
}
if(!current.right){
return current.left
}
root.value=this.minimum(current.right)
current.right=this.removeNode(current.right,current.value)
}
return current
}
minimum(current){
if(!current.left){
return current.value
}else{
return this.minimum(current.left)
}
}
inorder(current){
if(current!==null){
this.inorder(current.left)
console.log(current.value);
this.inorder(current.right)
}
}
}
let bt=new binaryTree
bt.insert(20)
bt.insert(15)
bt.insert(25)
console.log("inorder")
bt.inorder(bt.root)
bt.remove(25)
console.log(bt.root);