Java中的红黑树规则执行
我试图用Java实现一个红黑树。为了做到这一点,我允许每次插入都像BST一样进行,然后在插入后我预先排序遍历树并检查每个节点(我在字典应用程序中使用它时称之为单词)是否满足红黑规则。目前看来是这样的Java中的红黑树规则执行,java,tree,red-black-tree,Java,Tree,Red Black Tree,我试图用Java实现一个红黑树。为了做到这一点,我允许每次插入都像BST一样进行,然后在插入后我预先排序遍历树并检查每个节点(我在字典应用程序中使用它时称之为单词)是否满足红黑规则。目前看来是这样的 private void checkRedBlackRules(Word w) { //Checking for Red-Red sequence Word leftChild = w.getLeft(); Word rightChild
private void checkRedBlackRules(Word w)
{
//Checking for Red-Red sequence
Word leftChild = w.getLeft();
Word rightChild = w.getRight();
Word leftleftGC, leftrightGC, rightleftGC, rightrightGC;
if(leftChild != null)
{
leftleftGC = leftChild.getLeft();
leftrightGC = leftChild.getRight();
}
else
{
leftleftGC = null;
leftrightGC = null;
}
if(rightChild != null)
{
rightleftGC = rightChild.getLeft();
rightrightGC = rightChild.getRight();
}
else
{
rightleftGC = null;
rightrightGC = null;
}
try
{
if(leftChild.isRed() && leftleftGC.isRed())
{
rotateRight(w, leftChild, leftleftGC);
}
}
catch(NullPointerException e) {}
try
{
if(leftChild.isRed() && leftrightGC.isRed())
{
}
}
catch(NullPointerException e) {}
try
{
if(rightChild.isRed() && rightleftGC.isRed())
{
}
}
catch(NullPointerException e) {}
try
{
if(rightChild.isRed() && rightrightGC.isRed())
{
rotateLeft(w, leftChild, leftrightGC);
}
}
catch(NullPointerException e) {}
if(w.getLeft() != null)
checkRedBlackRules(w.getLeft());
if(w.getRight() != null)
checkRedBlackRules(w.getRight());
}
private void rotateLeft(Word parent, Word child, Word grandChild)
{
child = parent;
child.setLeft(parent);
child.setRight(grandChild);
}
private void rotateRight(Word parent, Word child, Word grandChild)
{
child = parent;
child.setLeft(grandChild);
child.setRight(parent);
}
但是,当我尝试向树中添加两个以上的元素时,它会陷入一个无休止的循环中,直到发生StackOverflow错误。没有详细介绍所有逻辑,旋转函数在我看来是不正确的:
private void rotateLeft(Word parent, Word child, Word grandChild)
{
child = parent;
child.setLeft(parent);
child.setRight(grandChild);
}
不使用子参数,而是立即将其设置为父参数。这意味着,当您调用child.setLeft(parent)时,您正在将原始父级的左子级设置为自身,我认为这是导致无限循环(从而导致堆栈溢出)的原因。为什么不加区分地捕获并忽略
NullPointerException
s?这绝对不是正确的做法。旋转函数看起来很奇怪<代码>子=父;子。setLeft(父)就像说parent.setLeft(parent)代码>。