Find the Distance Between Two Nodes in a Binary Tree - Algorithm & Examples

Problem Statement

Given a binary tree and two node values n1 and n2, find the number of edges in the shortest path between them. The distance between two nodes in a binary tree is defined as the number of edges in the path from one node to another.

If either node does not exist in the tree, return -1.

Examples

Input Tree Node 1 Node 2 Distance Description
[1, 2, 3, 4, 5, 6, 7]
4 5 2 LCA is 2. Distance = depth(4) + depth(5) - 2 × depth(2) = 2 + 2 - 2 = 2
[1, 2, 3, null, 4, null, 5]
4 5 4 LCA is 1. Path: 4 → 2 → 1 → 3 → 5 (4 steps)
[10, 5, 15, 3, 7, null, 18]
3 7 2 LCA is 5. Path: 3 → 5 → 7 = 2 steps
[1, 2, 3, 4, null, null, 5]
4 5 4 LCA is 1. Path: 4 → 2 → 1 → 3 → 5 = 4 steps
[1, 2, null, 3, null, 4]
3 4 2 LCA is 3. Distance from 3 to 4 is 1, from 3 to 3 is 0 → total = 1 + 1 = 2
[7]
7 7 0 Both nodes are the same → distance is 0

Solution

Case 1: Normal Case — Both Nodes Exist and Are Different

To find the distance between two distinct nodes in a binary tree, we first need to locate their Lowest Common Ancestor (LCA). The LCA is the deepest node that is an ancestor of both target nodes. Once we have the LCA, we compute the distance from the LCA to each of the two nodes separately, then sum them up.

For example, in the tree:

      1
     / \
    2   3
   / \
  4   5

The distance between 4 and 5 is 2 (Path: 4 → 2 → 5). LCA is 2, and each node is one edge away from it.

Case 2: One Node is Ancestor of the Other

When one of the nodes is an ancestor of the other, the LCA is the ancestor node itself. In that case, the distance is simply the depth difference between the two nodes. For instance, in the same tree, the distance between 2 and 5 is 1 because 2 is the parent of 5.

Case 3: Same Node

If the two input node values are the same, then the distance is obviously 0, since we are at the same position in the tree. No traversal is needed.

Case 4: Empty Tree

If the tree is empty (null root), then there is no node to compare. In such cases, we return -1 as both nodes are non-existent by default.

Case 5: One or Both Nodes Not Present

If one or both of the nodes are missing from the tree, we should not proceed with distance calculation. Instead, we return -1 indicating the operation is not valid because required data is missing. Always verify presence before processing.

Algorithm Steps

  1. Given a binary tree and two target node values.
  2. Find the lowest common ancestor (LCA) of the two nodes.
  3. Compute the distance from the LCA to the first node.
  4. Compute the distance from the LCA to the second node.
  5. The distance between the two nodes is the sum of these two distances.

Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def lowestCommonAncestor(root, n1, n2):
    if not root or root.val == n1 or root.val == n2:
        return root
    left = lowestCommonAncestor(root.left, n1, n2)
    right = lowestCommonAncestor(root.right, n1, n2)
    if left and right:
        return root
    return left if left else right

def distanceFromRoot(root, target, distance):
    if not root:
        return -1
    if root.val == target:
        return distance
    left = distanceFromRoot(root.left, target, distance + 1)
    if left != -1:
        return left
    return distanceFromRoot(root.right, target, distance + 1)

def distanceBetweenNodes(root, n1, n2):
    lca = lowestCommonAncestor(root, n1, n2)
    d1 = distanceFromRoot(lca, n1, 0)
    d2 = distanceFromRoot(lca, n2, 0)
    return d1 + d2

if __name__ == '__main__':
    # Construct binary tree:
    #         1
    #        / \
    #       2   3
    #      / \   
    #     4   5  
    root = TreeNode(1)
    root.left = TreeNode(2, TreeNode(4), TreeNode(5))
    root.right = TreeNode(3)
    print(distanceBetweenNodes(root, 4, 5))  # Expected output: 2