MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / pushHelper

Method pushHelper

structure/tree/avl.go:174–222  ·  view source on GitHub ↗
(root *AVLNode[T], key T)

Source from the content-addressed store, hash-verified

172}
173
174func (avl *AVL[T]) pushHelper(root *AVLNode[T], key T) *AVLNode[T] {
175 if root == avl._NIL {
176 return &AVLNode[T]{
177 key: key,
178 left: avl._NIL,
179 right: avl._NIL,
180 parent: avl._NIL,
181 height: 1,
182 }
183 }
184
185 switch {
186 case key < root.key:
187 tmp := avl.pushHelper(root.left, key)
188 tmp.parent = root
189 root.left = tmp
190 case key > root.key:
191 tmp := avl.pushHelper(root.right, key)
192 tmp.parent = root
193 root.right = tmp
194 default:
195 return root
196 }
197
198 // balance the tree
199 root.height = avl.height(root)
200 bFactor := avl.balanceFactor(root)
201 if bFactor > 1 {
202 switch {
203 case key < root.left.key:
204 return avl.rightRotate(root)
205 case key > root.left.key:
206 root.left = avl.leftRotate(root.left)
207 return avl.rightRotate(root)
208 }
209 }
210
211 if bFactor < -1 {
212 switch {
213 case key > root.right.key:
214 return avl.leftRotate(root)
215 case key < root.right.key:
216 root.right = avl.rightRotate(root.right)
217 return avl.leftRotate(root)
218 }
219 }
220
221 return root
222}
223
224func (avl *AVL[T]) deleteHelper(root *AVLNode[T], key T) *AVLNode[T] {
225 if root == avl._NIL {

Callers 1

PushMethod · 0.95

Calls 4

heightMethod · 0.95
balanceFactorMethod · 0.95
rightRotateMethod · 0.95
leftRotateMethod · 0.95

Tested by

no test coverage detected