问题描述
我正在学习树图中 remove() 的源代码。 但有一点我无法理解。
//....................忽略主要代码,留下这些
private void deleteEntry(Entry<K,V> p) {
if (p.left != null && p.right != null) {
Entry<K,V> s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
}
}
static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {`enter code here`
if (t == null)
return null;
else if (t.right != null) {
Entry<K,V> p = t.right;
while (p.left != null)
p = p.left;
return p;
} else {
Entry<K,V> p = t.parent;
Entry<K,V> ch = t;
while (p != null && ch == p.right) {
ch = p;
p = p.parent;
}
return p;
}
}
我对 deleteEntry 函数感到困惑,p 有 2 个孩子。 P.left 和 P.right 都不为空。 但是为什么它会判断 t.right 在后继函数中不为空呢? 我的意思是这是绝对的事实。 因为 t.right 必须不为空。 代码永远不会在后继函数中的 else master 中执行。
谁打电话告诉我我的问题在哪里? 谢谢你们。
1楼
如果您查看 TreeMap.java ,您会知道从许多地方调用后继程序,delete() 只是这样的一个地方。