在紅黑樹中,旋轉時,您需要知道誰是特定節點的父節點。 但是,節點只能引用右側或左側的子節點。紅黑樹 - 如何找到節點的父節點?
我想給一個節點實例變量「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