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.