【发布时间】:2017-01-26 04:11:54
【问题描述】:
我正在尝试实现 RedBlack 树插入方法,但它没有按预期工作。这是源代码。
插入方法:
void insert( int key ) { root = insert( null, root, key ); root.color = BLACK; }
private Node insert( Node parent, Node root, int key )
{
//STEP 1 : Classic BST insertion
if ( root == null )
return ( new Node( parent, key, RED ) );
boolean isLeft;
if ( key < root.key )
{
root.left = insert( root, root.left, key);
isLeft = true;
}
else
{
root.right = insert( root, root.right, key);
isLeft = false;
}
//STEP2: Self balancing the tree.
if ( isLeft )
{
if ( root.color == RED && root.left.color == RED )
{
Node sibling = findSibling( root );
if ( ! isRed( sibling ) )
{
if ( isLeftChild( root ) )
{
return rightRotate( root, true );
}
else
{
//recolore( root );
}
}
}
}
else
{
// mirror case
// yet to do
}
return root;
}
RightRotate 方法 + 其他使用的方法:
private Node rightRotate( Node newRoot, boolean changeColor )
{
Node oldRoot = newRoot.parent;
oldRoot.left = newRoot.right;
newRoot.right = oldRoot;
newRoot.parent = oldRoot.parent;
oldRoot.parent = newRoot;
if ( changeColor )
{
root.color = BLACK;
root.parent.color = RED;
}
return newRoot;
}
private Node findSibling( Node root )
{
Node parent = root.parent;
if ( parent.left == root )
return parent.right;
return parent.left;
}
private boolean isRed( Node root )
{
if ( root == null )
return false;
return root.color == RED;
}
private boolean isLeftChild( Node root )
{
if ( root.parent == null )
return false;
if ( root.parent.left == root )
return true;
return false;
}
树的主 + 前置打印:
void preOrder() { preOrder( root ); }
private void preOrder( Node root )
{
if ( root != null )
{
System.out.print( " | " + ( root.color ? "RED" : "BLACK" ) + " " + root.key + " |" );
preOrder( root.left );
preOrder( root.right );
}
}
}
class Main
{
public static void main( String[] args )
{
RedBlackBST tree = new RedBlackBST();
tree.insert( 3 );
tree.insert( 2 );
tree.insert( 1 );
tree.preOrder();
}
}
这个实现还没有完成,应该只适用于 Left Left 情况(如在主要方法 3,2,1 中),这意味着我必须进行右旋转。
预期的输出应该是:
| BLACK 2 | | RED 1 | | RED 3 |
我得到的不是这个输出
| BLACK 3 | | BLACK 2 | | RED 1 | | BLACK 3 | | BLACK 2 | | RED 1 | ... // infinity loop
谁能告诉我哪里出错了?显然,我不希望您发布整个代码,而只是提出如何解决该问题以及为什么它不起作用的建议。
【问题讨论】:
标签: java data-structures red-black-tree