How can we find the distances between every pair of nodes given a graph with N nodes and M edges?

I believe that trees introduce many simplifications, especially since there’s only one simple path between any two nodes. Can we achieve this task in O(N+M) using a *single DFS call* on a tree?

Please explain how we can achieve this with DFS on a tree, and please provide some example code. Thank you!