高,我最熟悉 C 和 C++,但我最近一直在尝试使用 java。
我的问题是这条线if (parent.leftChild == temp)
永远不是真的。虽然parent.leftChild.Key = temp.key
(其余内容相同),但我的印象是,问题在于 Eclipse 调试器中的 parent.leftChild 的 ID = ...5792,而 temp 的 ID 为 ...3632。
我希望有人可以进一步解释。我的代码的解决方法总是可以将 if 语句更改为if (parent.leftChild.key = temp.key)
,但不应该parent.left == temp
是有效的?
class Node{
int key;
char color;
Node leftChild;
Node rightChild;
Node parent;
//...constructors..//
}
private Node GetParent(Node node){
if(node != null)
return node.parent;
else
return null;
}
private void RemoveNodeFromTree(Node myNode){
Node temp = new Node(myNode);
//traverse
if(temp.leftChild!= null){
temp = temp.leftChild;
while(temp.rightChild!= null)
temp = temp.rightChild;
myNode.key = temp.key;
}
else if(temp.rightChild != null)
myNode.key = temp.rightChild.key;
Node parent = GetParent(temp);
Node childL = temp.leftChild;
Node childR = temp.rightChild;
//have parent point to the proper new node.
//parent points to left if it exists, then it tries right.
//if both are null, point to right anyway
if(parent !=null ){
//replace temp with it's left child
if(childL!= null){
if (parent.leftChild == temp)
parent.leftChild = childL;
else
parent.rightChild = childL;
childL.parent = parent;
childL.color = 'B';
if(childL.color == 'B' && temp.color == 'B')
DoubleBlackRestructure(childL, parent);
}
else //replace temp with it's right child
{
if (parent.leftChild == temp)
parent.leftChild = childR;
else
parent.rightChild = childR;
if(childR!= null)
childR.parent = parent;
if((childR == null || childR.color == 'B') && temp.color == 'B')
{
if(childR != null)
childR.color = 'B';
DoubleBlackRestructure(childR, parent);
}
else if (childR != null)
childR.color = 'B';
}
}
else
myNode = null;
temp = null;
}