如果对于一棵树的每个节点,从树到叶节点的最长路径比最短的树长不超过两倍,则该树具有红黑颜色。
这是一种计算任何节点颜色的算法 n
if n is root,
n.color = black
n.black-quota = height n / 2, rounded up.
else if n.parent is red,
n.color = black
n.black-quota = n.parent.black-quota.
else (n.parent is black)
if n.min-height < n.parent.black-quota, then
error "shortest path was too short"
else if n.min-height = n.parent.black-quota then
n.color = black
else (n.min-height > n.parent.black-quota)
n.color = red
either way,
n.black-quota = n.parent.black-quota - 1
这n.black-quota
是您希望看到的从节点到叶子的黑色节点数,n
并且n.min-height
是到最近叶子的距离。
为简便起见,令,h (n )=和m (n )=。b(n)= n.black-quota
h(n)= n.height
m(n)= n.min-height
定理:修正了一个二叉树。如果为每个节点Ñ ∈ Ť,ħ (Ñ )≤ 2 米(Ñ )和节点- [R = 根(Ť ),b ([R )∈ [ 1Tn∈Th(n)≤2m(n)r=root(T)则T具有红黑色,从根到叶的每条路径上都有正好是b(r)个黑色节点。b(r)∈[12h(r),m(r)]Tb(r)
证明:对。b(n)
验证高度为1或2的所有四棵树均满足定理。b(n)=1
根据红黑树的定义,根是黑色。令为具有黑色父级p的节点,使得b (p )∈ [ 1np。然后b(Ñ)=b(p)-1,ħ(Ñ)=^ h(p)-1和^ h(Ñ)≥米(Ñ)≥米(p)-1。b(p)∈[12h(p),m(p)]b(n)=b(p)−1h(n)=h(p)−1h(n)≥m(n)≥m(p)−1
假设该定理对于所有根为树成立,b (r )< b (qr。b(r)<b(q)
如果,则nb(n)=m(n)n根据归纳假设可以为红黑色。
如果然后b(n)=⌈b(p)=12h(p)。n不满足归纳假设,因此必须为红色。令c为n的子代。h(c)=h(p)−2和 b(c)=b(p)−1=1b(n)=⌈12h(n)⌉−1ncnh(c)=h(p)−2。然后b(c)=b(p)−1=12h(p)−1=12h(c)c can be red-black colored by the inductive assumption.
Note that, by the same reasoning, if b(n)∈(12h(r),m(r)), then both n and a child of n satisfy the inductive assumption. Therefore n could have any color.