Preimage $f^{-1}(v)$ of any value $v$ is a closed set, hence its complement $U(v)$ is open. This open set $U(v)$ is a disjoint union of intervals. If some interval is finite, say $(a,b)$, then $f(a)=f(b)=v$, but $f(c)\ne v$ for $a<c<b$. So, all intervals in $U(v)$ are infinite. Hence preimage of $v$ is connected: it is either a segment (possibly a single point), or a ray. Now we prove that $f$ is monotone. It suffices to prove that $f$ is monotone on any three points $\{a<b<c\}$. Assume the contrary, for example, $f(b)>\max(f(a),f(c))$. Then there is $v$ such that $f(b)>v>\max(f(a),f(c))$$f(b)>v:=\max(f(a),f(c))$. We see that $f^{-1}(v)$ is not connected: it contains points on $(a,b)$$[a,b)$ and $(b,c)$$(b,c]$, but does not contain $v$$b$.