Given a binary tree, determine the distance between given pairs of nodes in it. The distance between two nodes is defined as the total number of edges in the shortest path from one node to other.

For example, consider the binary tree. The distance between node 7 and node 6 is 3.

 
Distance between two nodes in binary tree

Practice this problem

This problem is a standard application of the lowest common ancestor of given nodes. 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.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

3

Java


Download  Run Code

Output:

3

Python


Download  Run Code

Output:

3

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.