The question is to find out sum of distances between every two nodes of BinarySearchTree given that every parent-child pair is separated by unit distance. It is to be calculated
If you mean O(n) per each insertion, then it can be done, assuming you do it after each and every insertion, starting with the root.
0- Record the current sum of the distances. Call it s1: O(1).
1- Insert the new node: O(n).
2- Perform a BFS, starting at this new node.
For each new node you discover, record its distance to the start (new) node, as BFS always does: O(n).
This gives you an array of the distances from the start node to all other nodes.
3- Sum these distances up. Call this s2: O(n).
4- New_sum = s1 + s2: O(1).
This algorithm is thus O(n).