Pick any node and assume it's the root. Run a DFS to find the distance to the furthest leaf. This will basically calculate the height of the tree if you pick the first node as root.
Next you find the proper root by finding the center of the tree. To do this you look at the children of the current root and pick the one with the largest height (largest distance to the furthest leaf). If you move the root to that child the new height will be min between the value you already have in that node and 1 + the next largest value from the other leafs of the current root. You apply this, moving the root until you can't decrease the height anymore. That is one center of the tree (could be more) and a solution that you are looking for.
The inital DFS is O(N). When optimizing the distance you can't visit a node twice and each step is O(1) amortized, so overall it's O(N). O(1) amortized because a node can have lots of children but you only consider them once (after you move you can't go back so you can't check them again) so even if you check the entire tree you'll check O(N) children in total.