Focus on the fact that in a tree, “number of connected components = number of vertices - number of edges”. Intuitively, it can be understood as: when vertices increase, the number of connected components increases by 1, and when edges increase, the number of connected components decreases by 1. $f(L, R)$ can also be found using this.
$$ \begin{aligned} &f(L, R) \\ &= Number of points contained in interval [L \ R] \\ &- Number of edges with both endpoints in interval [L \ R] \\ \end{aligned} $$
Find this for all combinations of L and R and take the sum. The number of vertices and edges can be found independently.
$$ \begin{aligned} &\sum_{L,R} f(L,R) \\ &= \sum_{L,R} Number of vertices in interval [L \ R] \\ &- \sum_{L,R} Number of edges with both endpoints in interval [L \ R] \\ &= V - E \end{aligned} $$
When illustrated as follows, a certain vertex $i$ appears $(i+1)(N-i)$ times in total, so take the sum of this for all $i$ to get $V$. Similarly, a certain edge $(u, v)$ appears $(u+1)(N-v)$ times in total, so take the sum for all edges to get $E$. $V-E$ is the answer.