@@ -18,13 +18,19 @@ BST.prototype.insert = function (value) {
18
18
19
19
while ( x !== null ) {
20
20
current = x
21
- if ( node . key < x . key ) x = x . left
22
- else x = x . right
21
+ if ( node . key < x . key )
22
+ x = x . left
23
+ else
24
+ x = x . right
23
25
}
24
26
25
- if ( current === null ) this . root = node
26
- else if ( node . key < current . key ) current . left = node
27
- else current . right = node
27
+ if ( current === null )
28
+ this . root = node
29
+ else if ( node . key < current . key )
30
+ current . left = node
31
+ else
32
+ current . right = node
33
+
28
34
node . parent = current
29
35
}
30
36
@@ -64,39 +70,49 @@ BST.prototype.transplant = function (u, v) {
64
70
BST . prototype . search = function ( value ) {
65
71
let current = this . root
66
72
while ( current ) {
67
- if ( value === current . key ) return current
68
- else if ( value < current . key ) current = current . left
69
- else current = current . right
73
+ if ( value === current . key )
74
+ return current
75
+ else if ( value < current . key )
76
+ current = current . left
77
+ else
78
+ current = current . right
70
79
}
71
80
return null
72
81
}
73
82
74
83
BST . prototype . min = function ( node ) {
75
- while ( node . left ) node = node . left
84
+ while ( node . left )
85
+ node = node . left
86
+
76
87
return node
77
88
}
78
89
79
90
BST . prototype . max = function ( node ) {
80
- while ( node . right ) node = node . right
91
+ while ( node . right )
92
+ node = node . right
93
+
81
94
return node
82
95
}
83
96
84
97
BST . prototype . sucessor = function ( value ) {
85
98
let current = this . search ( value )
86
- if ( current . right ) {
99
+ if ( current . right )
87
100
return this . min ( current . right )
88
- }
101
+
89
102
while ( current . parent && current === current . parent . right )
90
103
current = current . parent
104
+
91
105
return current . parent
92
106
}
93
107
94
108
BST . prototype . predecessor = function ( value ) {
95
109
let current = this . search ( value )
96
110
if ( current . left )
97
111
return this . max ( current . left )
112
+
98
113
while ( current . parent && current === current . parent . left )
99
114
current = current . parent
115
+
100
116
return current . parent
101
117
}
102
118
0 commit comments