-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.go
More file actions
34 lines (25 loc) · 702 Bytes
/
insert.go
File metadata and controls
34 lines (25 loc) · 702 Bytes
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
package avltree
func (tree *AVLTree[K, V]) Insert(key K, value V) {
node := &Node[K, V]{
Key: key,
Value: value,
}
tree.root = tree.insert(tree.root, node, tree.threshold)
}
func (tree *AVLTree[K, V]) insert(subtree *Node[K, V], node *Node[K, V], threshold int) *Node[K, V] {
if subtree == nil {
tree.size++
return node
}
if node.Key == subtree.Key {
subtree.Value = node.Value
return subtree
}
if node.Key < subtree.Key {
subtree.Left = tree.insert(subtree.Left, node, threshold)
} else {
subtree.Right = tree.insert(subtree.Right, node, threshold)
}
subtree.Height = 1 + max(heightOf(subtree.Left), heightOf(subtree.Right))
return balance(subtree, threshold)
}