【发布时间】:2012-06-03 17:37:56
【问题描述】:
基于此实现 http://pastebin.com/Gg3YbPUg,我无法理解 redbacktrees。
/**
* Insert into the tree.
* @param item the item to insert.
* @throws DuplicateItemException if item is already present.
*/
public void insert( AnyType item )
{
current = parent = grand = header;
nullNode.element = item;
while( compare( item, current ) != 0 )
{
great = grand; grand = parent; parent = current;
current = compare( item, current ) < 0 ?
current.left : current.right;
// Check if two red children; fix if so
if( current.left.color == RED && current.right.color == RED )
handleReorient( item );
}
// Insertion fails if already present
if( current != nullNode )
throw new DuplicateItemException( item.toString( ) );
current = new RedBlackNode<AnyType>( item, nullNode, nullNode );
// Attach to parent
if( compare( item, parent ) < 0 )
parent.left = current;
else
parent.right = current;
handleReorient( item );
}
我刚刚用数字 1,14,15,2,11,7,5,8 制作了一棵简单的树
// Test program
public static void main( String [ ] args )
{
RedBlackTree<Integer> t = new RedBlackTree<Integer>( );
t.insert(1);
t.insert(14);
t.insert(15);
t.insert(2);
t.insert(11);
t.insert(7);
t.insert(5);
t.insert(8);
t.printTree();
}
根据http://www.cs.auckland.ac.nz/software/AlgAnim/red_black.html 的示例,我的树应该看起来像...
还有我的 printTree 函数的控制台输出
/**
* Print all items.
*/
public void printTree( )
{
printTree( header.right );
}
/**
* Internal method to print a subtree in sorted order.
* @param t the node that roots the tree.
*/
private void printTree( RedBlackNode<AnyType> t )
{
if( t != nullNode )
{
printTree( t.left );
System.out.println("main element is <" + t.element + "("+t.color+")> left <" + t.left.element +"> right <" + t.right.element + ">" );
printTree( t.right );
}
}
是……
main element is <1(COLOR:RED)> left <8> right <8>
main element is <2(COLOR:BLACK)> left <1> right <5>
main element is <5(COLOR:RED)> left <8> right <8>
main element is <7(COLOR:RED)> left <2> right <14>
main element is <8(COLOR:BLACK)> left <8> right <8>
main element is <11(COLOR:RED)> left <8> right <8>
main element is <14(COLOR:BLACK)> left <11> right <15>
main element is <15(COLOR:RED)> left <8> right <8>
(出于阅读目的,我将 0 和 1 重命名为 COLOR RED AND BLACK) 据我了解,“标题”变量是树的根。
如果我要做类似的事情
public void function(AnyType x)
{
RedBlackNode<AnyType> n = find(x);
//what is the parent of n?
}
/**
* Find an item in the tree.
* @param x the item to search for.
* @return the matching item or null if not found.
*/
public RedBlackNode<AnyType> find( AnyType x )
{
nullNode.element = x;
current = header.right;
for( ; ; )
{
if( x.compareTo( current.element ) < 0 )
current = current.left;
else if( x.compareTo( current.element ) > 0 )
current = current.right;
else if( current != nullNode )
return current;
else
return null;
}
}
从上面 RedBlackTree 的 pastebin 实现中,我如何知道我当前的父元素对于 n 是什么?
【问题讨论】:
-
如果结构不正确,则问题出在您的
insert(...)方法中。请把它贴在上面,以便我们查看。 -
@HunterMcMillen 嘿猎人,一切都在提供的 pastebin 网址中。
标签: java red-black-tree