在红黑树中,旋转时,您需要知道谁是特定节点的父节点。 但是,节点只能引用右侧或左侧的子节点。红黑树 - 如何找到节点的父节点?
我想给一个节点实例变量“parent”,但正因为如此,我认为这样做不值得这样做,而且每转更改父引用也会太复杂。
public class Node {
private left;
private right;
private isRed;
private parent; //I don't think this is good idea
}
所以,我的解决方案是编写findParent()方法,使用搜索找到父。我想知道是否有其他方法来查找节点的父节点?
我的解决办法:
样本树:
50
/\
25 75
如果你想找到节点25的父母,你通过这样的:
Node parent = findParent(Node25.value);
并返回node50。
protected Node findParent(int val) {
if(root == null) {
return null;
}
Node current = root;
Node parent = current;
while(true) {
if(current.val == val) { //found
return parent;
}
if(current == null) { //not found
return null;
}
parent = current;
if(current.val > val) { //go left
current = current.left;
}
else { //go right
current = current.right;
}
}
}
我可能是错的,但我认为通常的办法是通过母公司的调用堆栈的旋转功能上的一个参数。 – mikera 2010-07-27 19:13:10
你应该看看libavl。正确的方法是在搜索时将祖先保存在堆栈中。 – user172818 2012-05-22 13:58:26