- FIX: checking insertion into red black tree

pull/1/head
emirpasic 11 years ago
parent 855ba6d469
commit 5cd4ddeb6d

@ -23,7 +23,6 @@ package redblacktree
import ( import (
"github.com/emirpasic/gods/utils" "github.com/emirpasic/gods/utils"
"log"
) )
type Color bool type Color bool
@ -166,14 +165,20 @@ func (node *Node) grandparent() *Node {
} }
func (node *Node) uncle() *Node { func (node *Node) uncle() *Node {
grandparent := node.grandparent() if node == nil || node.parent == nil || node.parent.parent == nil {
switch {
case grandparent == nil:
return nil return nil
case node.parent == grandparent.left: }
return grandparent.right return node.parent.sibling()
default: }
return grandparent.left
func (node *Node) sibling() *Node {
if node == nil || node.parent == nil {
return nil
}
if node == node.parent.left {
return node.parent.right
} else {
return node.parent.left
} }
} }
@ -230,10 +235,13 @@ func (tree *Tree) insertCase2(node *Node) {
} }
func (tree *Tree) insertCase3(node *Node) { func (tree *Tree) insertCase3(node *Node) {
log.Printf("%#v\n", node) uncle := node.uncle()
if node.uncle().color == RED { if uncle == nil {
return
}
if uncle.color == RED {
node.parent.color = BLACK node.parent.color = BLACK
node.uncle().color = BLACK uncle.color = BLACK
node.grandparent().color = RED node.grandparent().color = RED
tree.insertCase1(node.grandparent()) tree.insertCase1(node.grandparent())
} else { } else {
@ -257,26 +265,21 @@ func (tree *Tree) insertCase5(node *Node) {
node.grandparent().color = RED node.grandparent().color = RED
if node == node.parent.left && node.parent == node.grandparent().left { if node == node.parent.left && node.parent == node.grandparent().left {
tree.rotateRight(node.grandparent()) tree.rotateRight(node.grandparent())
} else { } else if node == node.parent.right && node.parent == node.grandparent().right {
tree.rotateLeft(node.grandparent()) tree.rotateLeft(node.grandparent())
} }
} }
func (node *Node) maximumNode() *Node { func (node *Node) maximumNode() *Node {
if node == nil {
return nil
}
for node.right != nil { for node.right != nil {
node = node.right node = node.right
} }
return node return node
} }
func (node *Node) sibling() *Node {
if node == node.parent.left {
return node.parent.right
} else {
return node.parent.left
}
}
func (tree *Tree) deleteCase1(node *Node) { func (tree *Tree) deleteCase1(node *Node) {
if node.parent == nil { if node.parent == nil {
return return

Loading…
Cancel
Save