Algorithm to find longest path in a tree that is smaller than x
Your dynamic program is a step in the right direction.
My idea would be to maintain two values for a node v:


$L_v$: The longest path starting from v going downwards (these corresponds to your dynamic program and the first two cases)
$U_v$: and the longest path in the subtree of v (i.e., case 3).


You already gave the formula for $L_v$.
For $U_v$ you take the maximum of $U_l$, $U_r$ and $L_l + w(lv) + w(rv) + L_r$ where $l$ and $r$ are the left and right children of v resp.
The last equation corresponds to the path which is formed by the longest paths to the left and to the right which are then joined.