These are two lineages in the Gospels. One - which you have cited - in Matthew, which traces Jesus' ancestry through Joseph, and another in Luke which traces His ancestry through Mary. Joseph's genealogy, however, also applies to Mary in that she, like he, was of the house and lineage of David (Luke 2:4).
John Chrysostom addresses your question directly in a 4th century homily on Matthew:
“But whence is it manifest that He is of David?” one may say. For if
He was not sprung of a man, but from a woman only, and the Virgin hath
not her genealogy traced, how shall we know that He was of David’s
race? Thus, there are two things inquired; both why His mother’s
genealogy is not recited, and wherefore it can be that Joseph is
mentioned by them, who hath no part in the birth: since the latter
seems to be superfluous, and the former a defect.
Of which then is it necessary to speak first? How the Virgin is of
David. How then shall we know that she is of David? Hearken unto God,
telling Gabriel to go unto “a virgin betrothed to a man (whose name
was Joseph), of the house and lineage of David.” What now wouldest
thou have plainer than this, when thou hast heard that the Virgin was
of the house and lineage of David?
Hence it is evident that Joseph also was of the same. Yes, for there
was a law, which bade that it should not be lawful to take a wife from
any other stock, but from the same tribe. And the patriarch Jacob also
foretold that He should arise out of the tribe of Judah, saying on
this wise: there shall not fail a ruler out of Judah, nor a governor
out of his loins, until He come for whom it is appointed, and He is
the expectation of the Gentiles.” [Genesis 49:10 LXX]
Homily II on Matthew