distance.go raw
1 package lattice
2
3 // TreeDistance is the hop count between two keys within one branch, measured
4 // through their lowest common ancestor node. 0 means both keys sit in the same
5 // node. Returns -1 if either key is absent.
6 func (t *Tree) TreeDistance(branch Branch, keyA, keyB Key) (int, error) {
7 if keyA == keyB {
8 return 0, nil
9 }
10 pathA, err := t.WalkPath(branch, keyA)
11 if err != nil {
12 return 0, err
13 }
14 pathB, err := t.WalkPath(branch, keyB)
15 if err != nil {
16 return 0, err
17 }
18 if pathA == nil || pathB == nil {
19 return -1, nil
20 }
21 lcaDepth := 0
22 minLen := len(pathA)
23 if len(pathB) < minLen {
24 minLen = len(pathB)
25 }
26 for i := 0; i < minLen; i++ {
27 if pathA[i] != pathB[i] {
28 break
29 }
30 lcaDepth = i
31 }
32 return (len(pathA) - 1 - lcaDepth) + (len(pathB) - 1 - lcaDepth), nil
33 }
34