-
Notifications
You must be signed in to change notification settings - Fork 2
/
join.go
39 lines (37 loc) · 841 Bytes
/
join.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
package splaytree
// Join two trees with cost O(N + M), which is optimal.
// After the join all unique elements of both trees are
// in the first tree. The second tree becomes empty.
func (tree *SplayTree) Join(other Interface) {
if other == nil {
return
}
oak := other.(*SplayTree)
if oak == tree {
return
}
tree.root = join(tree.root, oak.root)
oak.root = nil
}
func join(fir, oak *node) *node {
if fir == nil {
return oak
} else if oak == nil {
return fir
}
if fir.item.Less(oak.item) {
oak = join(fir.right, oak)
fir.right = nil
oak.left = join(fir, oak.left)
return oak
} else if oak.item.Less(fir.item) {
fir = join(fir, oak.right)
oak.right = nil
fir.left = join(fir.left, oak)
return fir
} else {
fir.left = join(fir.left, oak.left)
fir.right = join(fir.right, oak.right)
return fir
}
}