Skip to problem
←

Distance Between Two Tree Nodes

Medium 0 attempts

Given a binary tree with unique node values and two values a and b present in it, return the distance between those nodes, measured in edges.

The path may travel upward toward the root and then downward. A tree has exactly one simple path between any two nodes. If a and b are equal, return 0.

In Example 1, the path is 4 → 2 → 1 → 3 → 6. It contains five nodes but four edges, so return 4. Node values identify the targets; they are not edge weights.

Function contract

Implement findDist(root, a, b). The editor converts the level-order root array into nodes with val, left, and right. a and b are node values, not node objects.

Output: Return the number of edges on the unique path between a and b. Return 0 when a equals b.

Example 1

Input
root = [1,2,3,4,5,6,7]
a = 4
b = 6
Output
4

Example 2

Input
root = [1,2,3]
a = 2
b = 2
Output
0
Constraints
  • 1 <= number of nodes <= 10^4
  • Node values are unique integers from 1 through the number of nodes
  • a and b are values present in the tree; they may be equal

Parent Map and Ancestor Distances

Record parent pointers, then map the distance from a to each ancestor. Walk upward from b until reaching one of those ancestors; add the two distances. The first shared ancestor is the lowest common ancestor, so these two path segments form the unique path. Distances start at zero, making equal targets return zero. The explicit traversal stack avoids recursion overflow on a long chain.

javascript
function findDist(root, a, b) {
  const parent = new Map([[root, null]]),
    stack = [root];
  let an, bn;
  while (stack.length) {
    const node = stack.pop();
    if (node.val === a) an = node;
    if (node.val === b) bn = node;
    for (const child of [node.left, node.right])
      if (child) {
        parent.set(child, node);
        stack.push(child);
      }
  }
  const distance = new Map();
  let d = 0;
  while (an) {
    distance.set(an, d++);
    an = parent.get(an);
  }
  d = 0;
  while (!distance.has(bn)) {
    bn = parent.get(bn);
    d++;
  }
  return d + distance.get(bn);
}

Time: O(n) | Space: O(n) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript