title: Determine distance between two random nodes in a tree
body: <p>Given a general tree, I want the distance between two nodes <code>v</code> and <code>w</code>. </p>
  
  <p>Wikipedia <a href="http://en.wikipedia.org/wiki/Lowest_common_ancestor" rel="noreferrer">states the following</a>:</p>
  
  <blockquote>
    <p>Computation of lowest common ancestors may be useful, for instance, as part of a procedure for determining the distance between pairs of nodes in a tree: the distance from v to w can be computed as the distance from the root to v, plus the distance from the root to w, minus twice the distance from the root to their lowest common ancestor.</p>
  </blockquote>
  
  <p>Let's say <code>d(x)</code> denotes the distance of node <code>x</code> from the root which we set to <code>1</code>. <code>d(x,y)</code> denotes the distance between two vertices <code>x</code> and <code>y</code>. <code>lca(x,y)</code> denotes the lowest common ancestor of vertex pair <code>x</code> and <code>y</code>.</p>
  
  <p>Thus if we have <code>4</code> and <code>8</code>, <code>lca(4,8) = 2</code> therefore, according to the description above, <code>d(4,8) = d(4) + d(8) - 2 * d(lca(4,8)) = 2 + 3 - 2 * 1 = 3</code>. Great, that worked!</p>
  
  <p>However, the case stated above seems to fail for the vertex pair <code>(8,3)</code> (<code>lca(8,3) = 2</code>) <code>d(8,3) = d(8) + d(3) - 2 * d(2) = 3 + 1 - 2 * 1 = 2.</code> This is incorrect however, the distance <code>d(8,3) = 4</code> as can be seen on the graph. The algorithm seems to fail for anything that crosses over the defined root.</p>
  
  <p>What am I missing? </p>
  
  <p><img src="https://i.imgur.com/iSZAm1I.png" alt="enter image description here"></p>