赤黒木では、回転するとき、特定のノードの親が誰であるかを知る必要があります。ただし、ノードは右または左の子への参照しかありません。
ノードインスタンス変数に「親」を与えることを考えていましたが、この理由からそうする価値はないと思います。また、回転ごとに親参照を変更するのは複雑すぎるでしょう。
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;
}
}
}