【发布时间】:2011-03-21 19:03:20
【问题描述】:
在红黑树中,当旋转时,你需要知道谁是特定节点的父节点。 但是,该节点仅具有对右子或左子的引用。
我想给一个节点实例变量“父”,但正因为这个原因,我认为这样做不值得,而且每次旋转更改父引用也太复杂了。
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;
}
}
}
【问题讨论】:
-
我可能错了,但我认为通常的做法是将父级作为调用堆栈上的参数传递给旋转函数。
-
你应该看看 libavl。正确的方法是在搜索时将祖先保留在堆栈中。
标签: java parent red-black-tree