-
Notifications
You must be signed in to change notification settings - Fork 2
/
del.go
91 lines (86 loc) · 1.9 KB
/
del.go
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
package splaytree
// DeleteRoot removes the element which is currently at the root.
// Return nil if the tree was empty, else the root item.
func (tree *SplayTree) DeleteRoot() Item {
node := tree.root
if node == nil {
return nil
}
found := node.item
if node.left == nil {
tree.root = node.right
} else if node.right == nil {
tree.root = node.left
} else {
temp := node.right
tree.root = node.left
tree.splay(found)
tree.root.right = temp
}
return found
}
// Delete an item from the tree.
// Return the deleted item if it was found, else nil.
func (tree *SplayTree) Delete(item Item) Item {
if item == nil || tree.root == nil {
return nil
}
tree.splay(item)
if item.Less(tree.root.item) || tree.root.item.Less(item) {
return nil
}
return tree.DeleteRoot()
}
// DeleteAll deletes all given items.
// Return the number of deleted items.
func (tree *SplayTree) DeleteAll(items []Item) int {
num := 0
for _, item := range items {
if tree.Delete(item) != nil {
num++
}
}
return num
}
// DeleteMin deletes the smallest element from the tree.
// Return the smallest item if the tree was non-empty, else nil.
func (tree *SplayTree) DeleteMin() Item {
node := tree.root
if node == nil {
return nil
}
if node.left == nil {
tree.root = node.right
} else {
var parent = node
node = node.left
for node.left != nil {
parent = node
node = node.left
}
parent.left = node.right
tree.splay(parent.item)
}
return node.item
}
// DeleteMax deletes the largest element from the tree.
// Return the largest item if the tree was non-empty, else nil.
func (tree *SplayTree) DeleteMax() Item {
node := tree.root
if node == nil {
return nil
}
if node.right == nil {
tree.root = node.left
} else {
var parent = node
node = node.right
for node.right != nil {
parent = node
node = node.right
}
parent.right = node.left
tree.splay(parent.item)
}
return node.item
}