The z-spread is conceptually closely related to YTM. It is a more accurate definition of spread than the simple difference between two numbers, for the same reasons that YTM is a more accurate measure than flat yield: particularly changes in rates over time.
The z-spread is the amount by which the discount rate would need to exceed the return of risk free bonds in order for the present value to equal the market price.
Looking at this another way, the z-spread is an IRR. However, rather than discounting each cash flow (coupon payment) at the same rate, each is discounted by the rate over that term (i.e. read off the yield curve) plus the z-spread.
The calculation, assuming annual ocupon payments, is:
P = C0 + C1/(1+r1 + z) + C2/(1+r2 + z)2 + C3/(1+r3 + z)3 ... T(1+rn + z)n
Where P is the dirty price of the bond,
C1 is the first coupon payment, C1 the second etc.,
r1 is the risk free rate over the next year, r2 over the next two years, etc.,
T is the terminal value — the total payments in the year the bond matures, and
z is the z-spread.
The z-spread needs to be calculated starting from a guess that is progressively improved, using the same procedure as for IRR.