基本上,问题是我们如何在不一直到根部的情况下找出深度差异......
这并不是说你不能一直遍历到根。它只是说最终的结果可能不是根源。
首先,定义一个函数来确定一个节点的深度(伪代码):
function depthOf(r, p):
depth = 0
temp = p
while curr is not r:
depth++
temp = temp.parent
return depth
只需为两个节点调用此函数,然后获取差异。
作为附加功能,您可以使用此信息来查找最低共同祖先:
使用深度差从两个节点中最深的节点向上走,直到与另一个节点处于相同深度。从那时起,从两个节点串联向上走,直到从两侧到达同一个节点:
function least(r, p, q)
diff = depthOf(r, p) - depthOf(r, q) # The answer
# In order to find least common ancestor, continue as follows:
while diff > 0: # p is deeper than q
p = p.parent
diff--
while diff < 0: # q is deeper than p
q = q.parent
diff++
while p is not q:
p = p.parent
q = q.parent
return p