Merge pull request #3 from emirpasic/redblacktree-node-export

Red-Black Tree Extensions
pull/2/merge
Emir Pasic 9 years ago
commit 6fb76b553f

@ -39,19 +39,18 @@ type Interface interface {
Clear() Clear()
Values() []interface{} Values() []interface{}
} }
``` ```
Container specific operations: Container specific operations:
```go ```go
// Returns sorted container's elements with respect to the passed comparator. // Returns sorted container's elements with respect to the passed comparator.
// Does not effect the ordering of elements within the container. // Does not effect the ordering of elements within the container.
// Uses timsort. // Uses timsort.
func GetSortedValues(container Interface, comparator utils.Comparator) []interface{} { func GetSortedValues(container Interface, comparator utils.Comparator) []interface{} {
``` ```
####Sets ####Sets
A set is a data structure that can store elements and no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests an element for membership in a set. This structed is often used to ensure that no duplicates are present in a collection. A set is a data structure that can store elements and no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests an element for membership in a set. This structed is often used to ensure that no duplicates are present in a collection.
@ -96,8 +95,6 @@ func main() {
set.Empty() // true set.Empty() // true
set.Size() // 0 set.Size() // 0
} }
``` ```
#####TreeSet #####TreeSet
@ -125,7 +122,6 @@ func main() {
set.Empty() // true set.Empty() // true
set.Size() // 0 set.Size() // 0
} }
``` ```
####Lists ####Lists
@ -220,8 +216,6 @@ func main() {
list.Add("a") // ["a"] list.Add("a") // ["a"]
list.Clear() // [] list.Clear() // []
} }
``` ```
#####DoublyLinkedList #####DoublyLinkedList
@ -257,8 +251,6 @@ func main() {
list.Add("a") // ["a"] list.Add("a") // ["a"]
list.Clear() // [] list.Clear() // []
} }
``` ```
@ -279,14 +271,13 @@ type Interface interface {
// Clear() // Clear()
// Values() []interface{} // Values() []interface{}
} }
``` ```
#####LinkedListStack #####LinkedListStack
This stack structure is based on a linked list, i.e. each previous element has a point to the next. This stack structure is based on a linked list, i.e. each previous element has a point to the next.
All operations are guaranted constant time performance, except _Values()_, which is as always of linear time performance. All operations are guaranteed constant time performance, except _Values()_, which is as always of linear time performance.
```go ```go
package main package main
@ -307,7 +298,6 @@ func main() {
stack.Empty() // true stack.Empty() // true
stack.Size() // 0 stack.Size() // 0
} }
``` ```
#####ArrayStack #####ArrayStack
@ -335,8 +325,6 @@ func main() {
stack.Empty() // true stack.Empty() // true
stack.Size() // 0 stack.Size() // 0
} }
``` ```
####Maps ####Maps
@ -361,7 +349,7 @@ type Interface interface {
#####HashMap #####HashMap
Map structure based on hash tables, more exactly, Go's map. Keys are unordered. Map structure based on hash tables, more exactly, Go's map. Keys are unordered.
All operations are guaranted constant time performance, except _Key()_ and _Values()_ retrieval that of linear time performance. All operations are guaranted constant time performance, except _Key()_ and _Values()_ retrieval that of linear time performance.
@ -384,12 +372,11 @@ func main() {
m.Empty() // true m.Empty() // true
m.Size() // 0 m.Size() // 0
} }
``` ```
#####TreeMap #####TreeMap
Map structure based on our red-black tree implementation. Keys are ordered with respect to the passed comparator. Map structure based on our red-black tree implementation. Keys are ordered with respect to the passed comparator.
_Put()_, _Get()_ and _Remove()_ are guaranteed log(n) time performance. _Put()_, _Get()_ and _Remove()_ are guaranteed log(n) time performance.
@ -414,8 +401,6 @@ func main() {
m.Empty() // true m.Empty() // true
m.Size() // 0 m.Size() // 0
} }
``` ```
####Trees ####Trees
@ -432,7 +417,7 @@ type Interface interface {
// Values() []interface{} // Values() []interface{}
} }
``` ```
#####RedBlackTree #####RedBlackTree
A redblack tree is a binary search tree with an extra bit of data per node, its color, which can be either red or black. The extra bit of storage ensures an approximately balanced tree by constraining how nodes are colored from any path from the root to the leaf. Thus, it is a data structure which is a type of self-balancing binary search tree. A redblack tree is a binary search tree with an extra bit of data per node, its color, which can be either red or black. The extra bit of storage ensures an approximately balanced tree by constraining how nodes are colored from any path from the root to the leaf. Thus, it is a data structure which is a type of self-balancing binary search tree.
@ -487,9 +472,10 @@ func main() {
tree.Empty() // true tree.Empty() // true
tree.Size() // 0 tree.Size() // 0
} }
``` ```
Extending the red-black tree's functionality has been demonstrated in the following [example](https://github.com/emirpasic/gods/blob/master/examples/redblacktreeextended.go).
#####BinaryHeap #####BinaryHeap
A binary heap is a heap data structure created using a binary tree. It can be seen as a binary tree with two additional constraints: A binary heap is a heap data structure created using a binary tree. It can be seen as a binary tree with two additional constraints:
@ -558,7 +544,7 @@ Return values:
-1, if a < b -1, if a < b
0, if a == b 0, if a == b
1, if a > b 1, if a > b
Comparator signature: Comparator signature:
type Comparator func(a, b interface{}) int type Comparator func(a, b interface{}) int
@ -640,13 +626,13 @@ func byID(a, b interface{}) int {
} }
func main() { func main() {
set := treeset.NewWith(byID) set := treeset.NewWith(byID)
set.Add(User{2, "Second"}) set.Add(User{2, "Second"})
set.Add(User{3, "Third"}) set.Add(User{3, "Third"})
set.Add(User{1, "First"}) set.Add(User{1, "First"})
set.Add(User{4, "Fourth"}) set.Add(User{4, "Fourth"})
fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth} fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth}
} }
``` ```
@ -670,38 +656,37 @@ func main() {
strings = append(strings, "c") // ["d","a",b","c"] strings = append(strings, "c") // ["d","a",b","c"]
utils.Sort(strings, utils.StringComparator) // ["a","b","c","d"] utils.Sort(strings, utils.StringComparator) // ["a","b","c","d"]
} }
``` ```
## Motivations ## Motivations
Collections and data structures found in other languages: Java Collections, C++ Standard Template Library (STL) containers, Qt Containers, etc. Collections and data structures found in other languages: Java Collections, C++ Standard Template Library (STL) containers, Qt Containers, etc.
## Goals ## Goals
**Fast algorithms**: **Fast algorithms**:
- Based on decades of knowledge and experiences of other libraries mentioned above. - Based on decades of knowledge and experiences of other libraries mentioned above.
**Memory efficient algorithms**: **Memory efficient algorithms**:
- Avoiding to consume memory by using optimal algorithms and data structures for the given set of problems, e.g. red-black tree in case of TreeMap to avoid keeping redundant sorted array of keys in memory. - Avoiding to consume memory by using optimal algorithms and data structures for the given set of problems, e.g. red-black tree in case of TreeMap to avoid keeping redundant sorted array of keys in memory.
**Easy to use library**: **Easy to use library**:
- Well-structued library with minimalistic set of atomic operations from which more complex operations can be crafted. - Well-structured library with minimalistic set of atomic operations from which more complex operations can be crafted.
**Stable library**:
**Stable library**:
- Only additions are permitted keeping the library backward compatible. - Only additions are permitted keeping the library backward compatible.
**Solid documentation and examples**: **Solid documentation and examples**:
- Learning by example. - Learning by example.
**Production ready**: **Production ready**:
- Still waiting for the project to mature and be used in some heavy back-end tasks. - Used in production.
There is often a tug of war between speed and memory when crafting algorithms. We choose to optimize for speed in most cases within reasonable limits on memory consumption. There is often a tug of war between speed and memory when crafting algorithms. We choose to optimize for speed in most cases within reasonable limits on memory consumption.

@ -31,7 +31,7 @@ import (
rbt "github.com/emirpasic/gods/trees/redblacktree" rbt "github.com/emirpasic/gods/trees/redblacktree"
) )
func RedBlacTtreeExample() { func RedBlackTreeExample() {
tree := rbt.NewWithIntComparator() // empty(keys are of type int) tree := rbt.NewWithIntComparator() // empty(keys are of type int)
tree.Put(1, "x") // 1->x tree.Put(1, "x") // 1->x
@ -46,11 +46,11 @@ func RedBlacTtreeExample() {
// //
// RedBlackTree // RedBlackTree
// │ ┌── 6 // │ ┌── 6
// │ ┌── 5 // │ ┌── 5
// │ ┌── 4 // │ ┌── 4
// │ │ └── 3 // │ │ └── 3
// └── 2 // └── 2
// └── 1 // └── 1
_ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order) _ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order)
_ = tree.Keys() // []interface {}{1, 2, 3, 4, 5, 6} (in order) _ = tree.Keys() // []interface {}{1, 2, 3, 4, 5, 6} (in order)

@ -0,0 +1,135 @@
/*
Copyright (c) 2015, Emir Pasic
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package examples
import (
"fmt"
rbt "github.com/emirpasic/gods/trees/redblacktree"
)
type RedBlackTreeExtended struct {
*rbt.Tree
}
func (tree *RedBlackTreeExtended) GetMin() (value interface{}, found bool) {
node, found := tree.getMinFromNode(tree.Root)
if node != nil {
return node.Value, found
} else {
return nil, false
}
}
func (tree *RedBlackTreeExtended) GetMax() (value interface{}, found bool) {
node, found := tree.getMaxFromNode(tree.Root)
if node != nil {
return node.Value, found
} else {
return nil, false
}
}
func (tree *RedBlackTreeExtended) RemoveMin() (value interface{}, deleted bool) {
node, found := tree.getMinFromNode(tree.Root)
if found {
tree.Remove(node.Key)
return node.Value, found
} else {
return nil, false
}
}
func (tree *RedBlackTreeExtended) RemoveMax() (value interface{}, deleted bool) {
node, found := tree.getMaxFromNode(tree.Root)
if found {
tree.Remove(node.Key)
return node.Value, found
} else {
return nil, false
}
}
func (tree *RedBlackTreeExtended) getMinFromNode(node *rbt.Node) (foundNode *rbt.Node, found bool) {
if node == nil {
return nil, false
}
if node.Left == nil {
return node, true
} else {
return tree.getMinFromNode(node.Left)
}
}
func (tree *RedBlackTreeExtended) getMaxFromNode(node *rbt.Node) (foundNode *rbt.Node, found bool) {
if node == nil {
return nil, false
}
if node.Right == nil {
return node, true
} else {
return tree.getMaxFromNode(node.Right)
}
}
func print(tree *RedBlackTreeExtended) {
max, _ := tree.GetMax()
min, _ := tree.GetMin()
fmt.Printf("Value for max key: %v \n", max)
fmt.Printf("Value for min key: %v \n", min)
fmt.Println(tree)
}
func RedBlackTreeExtendedExample() {
tree := RedBlackTreeExtended{rbt.NewWithIntComparator()}
tree.Put(1, "a") // 1->x (in order)
tree.Put(2, "b") // 1->x, 2->b (in order)
tree.Put(3, "c") // 1->x, 2->b, 3->c (in order)
tree.Put(4, "d") // 1->x, 2->b, 3->c, 4->d (in order)
tree.Put(5, "e") // 1->x, 2->b, 3->c, 4->d, 5->e (in order)
print(&tree)
// Value for max key: e
// Value for min key: a
// RedBlackTree
// │ ┌── 5
// │ ┌── 4
// │ │ └── 3
// └── 2
// └── 1
tree.RemoveMin() // 2->b, 3->c, 4->d, 5->e (in order)
tree.RemoveMax() // 2->b, 3->c, 4->d (in order)
tree.RemoveMin() // 3->c, 4->d (in order)
tree.RemoveMax() // 3->c (in order)
print(&tree)
// Value for max key: c
// Value for min key: c
// RedBlackTree
// └── 3
}

@ -49,18 +49,18 @@ const (
) )
type Tree struct { type Tree struct {
root *node Root *Node
size int size int
comparator utils.Comparator comparator utils.Comparator
} }
type node struct { type Node struct {
key interface{} Key interface{}
value interface{} Value interface{}
color color color color
left *node Left *Node
right *node Right *Node
parent *node Parent *Node
} }
// Instantiates a red-black tree with the custom comparator. // Instantiates a red-black tree with the custom comparator.
@ -81,35 +81,35 @@ func NewWithStringComparator() *Tree {
// Inserts node into the tree. // Inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics. // Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) { func (tree *Tree) Put(key interface{}, value interface{}) {
insertedNode := &node{key: key, value: value, color: red} insertedNode := &Node{Key: key, Value: value, color: red}
if tree.root == nil { if tree.Root == nil {
tree.root = insertedNode tree.Root = insertedNode
} else { } else {
node := tree.root node := tree.Root
loop := true loop := true
for loop { for loop {
compare := tree.comparator(key, node.key) compare := tree.comparator(key, node.Key)
switch { switch {
case compare == 0: case compare == 0:
node.value = value node.Value = value
return return
case compare < 0: case compare < 0:
if node.left == nil { if node.Left == nil {
node.left = insertedNode node.Left = insertedNode
loop = false loop = false
} else { } else {
node = node.left node = node.Left
} }
case compare > 0: case compare > 0:
if node.right == nil { if node.Right == nil {
node.right = insertedNode node.Right = insertedNode
loop = false loop = false
} else { } else {
node = node.right node = node.Right
} }
} }
} }
insertedNode.parent = node insertedNode.Parent = node
} }
tree.insertCase1(insertedNode) tree.insertCase1(insertedNode)
tree.size += 1 tree.size += 1
@ -121,7 +121,7 @@ func (tree *Tree) Put(key interface{}, value interface{}) {
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) { func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
node := tree.lookup(key) node := tree.lookup(key)
if node != nil { if node != nil {
return node.value, true return node.Value, true
} }
return nil, false return nil, false
} }
@ -129,29 +129,29 @@ func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
// Remove the node from the tree by key. // Remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics. // Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) { func (tree *Tree) Remove(key interface{}) {
var child *node var child *Node
node := tree.lookup(key) node := tree.lookup(key)
if node == nil { if node == nil {
return return
} }
if node.left != nil && node.right != nil { if node.Left != nil && node.Right != nil {
pred := node.left.maximumNode() pred := node.Left.maximumNode()
node.key = pred.key node.Key = pred.Key
node.value = pred.value node.Value = pred.Value
node = pred node = pred
} }
if node.left == nil || node.right == nil { if node.Left == nil || node.Right == nil {
if node.right == nil { if node.Right == nil {
child = node.left child = node.Left
} else { } else {
child = node.right child = node.Right
} }
if node.color == black { if node.color == black {
node.color = nodeColor(child) node.color = nodeColor(child)
tree.deleteCase1(node) tree.deleteCase1(node)
} }
tree.replaceNode(node, child) tree.replaceNode(node, child)
if node.parent == nil && child != nil { if node.Parent == nil && child != nil {
child.color = black child.color = black
} }
} }
@ -172,7 +172,7 @@ func (tree *Tree) Size() int {
func (tree *Tree) Keys() []interface{} { func (tree *Tree) Keys() []interface{} {
keys := make([]interface{}, tree.size) keys := make([]interface{}, tree.size)
for i, node := range tree.inOrder() { for i, node := range tree.inOrder() {
keys[i] = node.key keys[i] = node.Key
} }
return keys return keys
} }
@ -181,48 +181,48 @@ func (tree *Tree) Keys() []interface{} {
func (tree *Tree) Values() []interface{} { func (tree *Tree) Values() []interface{} {
values := make([]interface{}, tree.size) values := make([]interface{}, tree.size)
for i, node := range tree.inOrder() { for i, node := range tree.inOrder() {
values[i] = node.value values[i] = node.Value
} }
return values return values
} }
// Removes all nodes from the tree. // Removes all nodes from the tree.
func (tree *Tree) Clear() { func (tree *Tree) Clear() {
tree.root = nil tree.Root = nil
tree.size = 0 tree.size = 0
} }
func (tree *Tree) String() string { func (tree *Tree) String() string {
str := "RedBlackTree\n" str := "RedBlackTree\n"
if !tree.Empty() { if !tree.Empty() {
output(tree.root, "", true, &str) output(tree.Root, "", true, &str)
} }
return str return str
} }
func (node *node) String() string { func (node *Node) String() string {
return fmt.Sprintf("%v", node.key) return fmt.Sprintf("%v", node.Key)
} }
// Returns all nodes in order // Returns all nodes in order
func (tree *Tree) inOrder() []*node { func (tree *Tree) inOrder() []*Node {
nodes := make([]*node, tree.size) nodes := make([]*Node, tree.size)
if tree.size > 0 { if tree.size > 0 {
current := tree.root current := tree.Root
stack := linkedliststack.New() stack := linkedliststack.New()
done := false done := false
count := 0 count := 0
for !done { for !done {
if current != nil { if current != nil {
stack.Push(current) stack.Push(current)
current = current.left current = current.Left
} else { } else {
if !stack.Empty() { if !stack.Empty() {
currentPop, _ := stack.Pop() currentPop, _ := stack.Pop()
current = currentPop.(*node) current = currentPop.(*Node)
nodes[count] = current nodes[count] = current
count += 1 count += 1
current = current.right current = current.Right
} else { } else {
done = true done = true
} }
@ -232,15 +232,15 @@ func (tree *Tree) inOrder() []*node {
return nodes return nodes
} }
func output(node *node, prefix string, isTail bool, str *string) { func output(node *Node, prefix string, isTail bool, str *string) {
if node.right != nil { if node.Right != nil {
newPrefix := prefix newPrefix := prefix
if isTail { if isTail {
newPrefix += "│ " newPrefix += "│ "
} else { } else {
newPrefix += " " newPrefix += " "
} }
output(node.right, newPrefix, false, str) output(node.Right, newPrefix, false, str)
} }
*str += prefix *str += prefix
if isTail { if isTail {
@ -249,114 +249,114 @@ func output(node *node, prefix string, isTail bool, str *string) {
*str += "┌── " *str += "┌── "
} }
*str += node.String() + "\n" *str += node.String() + "\n"
if node.left != nil { if node.Left != nil {
newPrefix := prefix newPrefix := prefix
if isTail { if isTail {
newPrefix += " " newPrefix += " "
} else { } else {
newPrefix += "│ " newPrefix += "│ "
} }
output(node.left, newPrefix, true, str) output(node.Left, newPrefix, true, str)
} }
} }
func (tree *Tree) lookup(key interface{}) *node { func (tree *Tree) lookup(key interface{}) *Node {
node := tree.root node := tree.Root
for node != nil { for node != nil {
compare := tree.comparator(key, node.key) compare := tree.comparator(key, node.Key)
switch { switch {
case compare == 0: case compare == 0:
return node return node
case compare < 0: case compare < 0:
node = node.left node = node.Left
case compare > 0: case compare > 0:
node = node.right node = node.Right
} }
} }
return nil return nil
} }
func (node *node) grandparent() *node { func (node *Node) grandparent() *Node {
if node != nil && node.parent != nil { if node != nil && node.Parent != nil {
return node.parent.parent return node.Parent.Parent
} }
return nil return nil
} }
func (node *node) uncle() *node { func (node *Node) uncle() *Node {
if node == nil || node.parent == nil || node.parent.parent == nil { if node == nil || node.Parent == nil || node.Parent.Parent == nil {
return nil return nil
} }
return node.parent.sibling() return node.Parent.sibling()
} }
func (node *node) sibling() *node { func (node *Node) sibling() *Node {
if node == nil || node.parent == nil { if node == nil || node.Parent == nil {
return nil return nil
} }
if node == node.parent.left { if node == node.Parent.Left {
return node.parent.right return node.Parent.Right
} else { } else {
return node.parent.left return node.Parent.Left
} }
} }
func (tree *Tree) rotateLeft(node *node) { func (tree *Tree) rotateLeft(node *Node) {
right := node.right right := node.Right
tree.replaceNode(node, right) tree.replaceNode(node, right)
node.right = right.left node.Right = right.Left
if right.left != nil { if right.Left != nil {
right.left.parent = node right.Left.Parent = node
} }
right.left = node right.Left = node
node.parent = right node.Parent = right
} }
func (tree *Tree) rotateRight(node *node) { func (tree *Tree) rotateRight(node *Node) {
left := node.left left := node.Left
tree.replaceNode(node, left) tree.replaceNode(node, left)
node.left = left.right node.Left = left.Right
if left.right != nil { if left.Right != nil {
left.right.parent = node left.Right.Parent = node
} }
left.right = node left.Right = node
node.parent = left node.Parent = left
} }
func (tree *Tree) replaceNode(old *node, new *node) { func (tree *Tree) replaceNode(old *Node, new *Node) {
if old.parent == nil { if old.Parent == nil {
tree.root = new tree.Root = new
} else { } else {
if old == old.parent.left { if old == old.Parent.Left {
old.parent.left = new old.Parent.Left = new
} else { } else {
old.parent.right = new old.Parent.Right = new
} }
} }
if new != nil { if new != nil {
new.parent = old.parent new.Parent = old.Parent
} }
} }
func (tree *Tree) insertCase1(node *node) { func (tree *Tree) insertCase1(node *Node) {
if node.parent == nil { if node.Parent == nil {
node.color = black node.color = black
} else { } else {
tree.insertCase2(node) tree.insertCase2(node)
} }
} }
func (tree *Tree) insertCase2(node *node) { func (tree *Tree) insertCase2(node *Node) {
if nodeColor(node.parent) == black { if nodeColor(node.Parent) == black {
return return
} }
tree.insertCase3(node) tree.insertCase3(node)
} }
func (tree *Tree) insertCase3(node *node) { func (tree *Tree) insertCase3(node *Node) {
uncle := node.uncle() uncle := node.uncle()
if nodeColor(uncle) == red { if nodeColor(uncle) == red {
node.parent.color = black node.Parent.color = black
uncle.color = black uncle.color = black
node.grandparent().color = red node.grandparent().color = red
tree.insertCase1(node.grandparent()) tree.insertCase1(node.grandparent())
@ -365,121 +365,121 @@ func (tree *Tree) insertCase3(node *node) {
} }
} }
func (tree *Tree) insertCase4(node *node) { func (tree *Tree) insertCase4(node *Node) {
grandparent := node.grandparent() grandparent := node.grandparent()
if node == node.parent.right && node.parent == grandparent.left { if node == node.Parent.Right && node.Parent == grandparent.Left {
tree.rotateLeft(node.parent) tree.rotateLeft(node.Parent)
node = node.left node = node.Left
} else if node == node.parent.left && node.parent == grandparent.right { } else if node == node.Parent.Left && node.Parent == grandparent.Right {
tree.rotateRight(node.parent) tree.rotateRight(node.Parent)
node = node.right node = node.Right
} }
tree.insertCase5(node) tree.insertCase5(node)
} }
func (tree *Tree) insertCase5(node *node) { func (tree *Tree) insertCase5(node *Node) {
node.parent.color = black node.Parent.color = black
grandparent := node.grandparent() grandparent := node.grandparent()
grandparent.color = red grandparent.color = red
if node == node.parent.left && node.parent == grandparent.left { if node == node.Parent.Left && node.Parent == grandparent.Left {
tree.rotateRight(grandparent) tree.rotateRight(grandparent)
} else if node == node.parent.right && node.parent == grandparent.right { } else if node == node.Parent.Right && node.Parent == grandparent.Right {
tree.rotateLeft(grandparent) tree.rotateLeft(grandparent)
} }
} }
func (node *node) maximumNode() *node { func (node *Node) maximumNode() *Node {
if node == nil { if node == nil {
return nil return nil
} }
for node.right != nil { for node.Right != nil {
node = node.right node = node.Right
} }
return node return node
} }
func (tree *Tree) deleteCase1(node *node) { func (tree *Tree) deleteCase1(node *Node) {
if node.parent == nil { if node.Parent == nil {
return return
} else { } else {
tree.deleteCase2(node) tree.deleteCase2(node)
} }
} }
func (tree *Tree) deleteCase2(node *node) { func (tree *Tree) deleteCase2(node *Node) {
sibling := node.sibling() sibling := node.sibling()
if nodeColor(sibling) == red { if nodeColor(sibling) == red {
node.parent.color = red node.Parent.color = red
sibling.color = black sibling.color = black
if node == node.parent.left { if node == node.Parent.Left {
tree.rotateLeft(node.parent) tree.rotateLeft(node.Parent)
} else { } else {
tree.rotateRight(node.parent) tree.rotateRight(node.Parent)
} }
} }
tree.deleteCase3(node) tree.deleteCase3(node)
} }
func (tree *Tree) deleteCase3(node *node) { func (tree *Tree) deleteCase3(node *Node) {
sibling := node.sibling() sibling := node.sibling()
if nodeColor(node.parent) == black && if nodeColor(node.Parent) == black &&
nodeColor(sibling) == black && nodeColor(sibling) == black &&
nodeColor(sibling.left) == black && nodeColor(sibling.Left) == black &&
nodeColor(sibling.right) == black { nodeColor(sibling.Right) == black {
sibling.color = red sibling.color = red
tree.deleteCase1(node.parent) tree.deleteCase1(node.Parent)
} else { } else {
tree.deleteCase4(node) tree.deleteCase4(node)
} }
} }
func (tree *Tree) deleteCase4(node *node) { func (tree *Tree) deleteCase4(node *Node) {
sibling := node.sibling() sibling := node.sibling()
if nodeColor(node.parent) == red && if nodeColor(node.Parent) == red &&
nodeColor(sibling) == black && nodeColor(sibling) == black &&
nodeColor(sibling.left) == black && nodeColor(sibling.Left) == black &&
nodeColor(sibling.right) == black { nodeColor(sibling.Right) == black {
sibling.color = red sibling.color = red
node.parent.color = black node.Parent.color = black
} else { } else {
tree.deleteCase5(node) tree.deleteCase5(node)
} }
} }
func (tree *Tree) deleteCase5(node *node) { func (tree *Tree) deleteCase5(node *Node) {
sibling := node.sibling() sibling := node.sibling()
if node == node.parent.left && if node == node.Parent.Left &&
nodeColor(sibling) == black && nodeColor(sibling) == black &&
nodeColor(sibling.left) == red && nodeColor(sibling.Left) == red &&
nodeColor(sibling.right) == black { nodeColor(sibling.Right) == black {
sibling.color = red sibling.color = red
sibling.left.color = black sibling.Left.color = black
tree.rotateRight(sibling) tree.rotateRight(sibling)
} else if node == node.parent.right && } else if node == node.Parent.Right &&
nodeColor(sibling) == black && nodeColor(sibling) == black &&
nodeColor(sibling.right) == red && nodeColor(sibling.Right) == red &&
nodeColor(sibling.left) == black { nodeColor(sibling.Left) == black {
sibling.color = red sibling.color = red
sibling.right.color = black sibling.Right.color = black
tree.rotateLeft(sibling) tree.rotateLeft(sibling)
} }
tree.deleteCase6(node) tree.deleteCase6(node)
} }
func (tree *Tree) deleteCase6(node *node) { func (tree *Tree) deleteCase6(node *Node) {
sibling := node.sibling() sibling := node.sibling()
sibling.color = nodeColor(node.parent) sibling.color = nodeColor(node.Parent)
node.parent.color = black node.Parent.color = black
if node == node.parent.left && nodeColor(sibling.right) == red { if node == node.Parent.Left && nodeColor(sibling.Right) == red {
sibling.right.color = black sibling.Right.color = black
tree.rotateLeft(node.parent) tree.rotateLeft(node.Parent)
} else if nodeColor(sibling.left) == red { } else if nodeColor(sibling.Left) == red {
sibling.left.color = black sibling.Left.color = black
tree.rotateRight(node.parent) tree.rotateRight(node.Parent)
} }
} }
func nodeColor(node *node) color { func nodeColor(node *Node) color {
if node == nil { if node == nil {
return black return black
} }

Loading…
Cancel
Save