【发布时间】:2017-11-23 22:32:18
【问题描述】:
我一直在寻找一种方法来检查红黑树的这个属性:“从节点到空节点的每条路径都必须包含相同数量的黑色节点”。
大多数赞成的答案如下所示:
// Return the black-height of node x. If its subtrees do not have
// the same black-height, call attention to it.
private int checkBlackHeight(Node x) {
if (x == null)
return 0;
else {
int leftBlackHeight = checkBlackHeight(x.left) +
(x.left.isBlack() ? 1 : 0);
int rightBlackHeight = checkBlackHeight(x.right) +
(x.right.isBlack() ? 1 : 0);
if (leftBlackHeight != rightBlackHeight)
complain("blackheight error", x);
return leftBlackHeight;
}
}
我感到困惑的是,这段代码不是只检查树下最左边和最右边的路径吗?它如何检查内部路径? 例如在下面的树中,它应该检查路径 11-9-8-.. 和 11-16-18... 但它是否检查 11-16-13-(一些内部节点)-...
11
/ \
9 16
/ \ / \
8 10 13 18
/\ /\ /\ / \
提前谢谢你!
【问题讨论】:
标签: algorithm data-structures tree