Is there a way to find path length to a node from root in a binary tree?
The worst case scenario for the algorithm is when you pick two nodes, N1 and N2 that have the longest path to the root node. In your example, two nodes whose common ancestor is J.
Say the length of the path of N1 and N2 is n and m.
Then the first while is O(n), the second one O(m) and finally the nested loop is O(nm).
So O(n) + O(m) + O(nm) = O(n*m).