Note David was sitting by then between the inner and outer gates (2 Sam 18:24). He was expecting a message about the fate of his son Absalom. He recalled the prophet Nathan announced to him the judgement of the Lord (2 Sam 12:11-14)
11 “This is what the Lord says: ‘Out of your own household I am going to bring calamity on you. Before your very eyes I will take your wives and give them to one who is close to you, and he will sleep with your wives in broad daylight.
12 You did it in secret, but I will do this thing in broad daylight before all Israel.’”
13 Then David said to Nathan, “I have sinned against the Lord.” Nathan replied, “The Lord has taken away your sin. You are not going to die.
14 But because by doing this you have shown utter contempt for the Lord, the son born to you will die.”
David remembered on that night, his firstborn with Bathsheba died. Now verse 11 was seen to have happened with Absalom, and what would the judgement on Absalom? Surely David knew it happened because of his sin.
As many agree that David was a compassionate, empathetic, and kind people in the Bible (using Dottard words), I want to suggest further that his character was due to his fear of the Lord, that he would not take the life of his enemies as a precaution to save his own life, which meant he trusted the Lord would always protect him.
However, his compassion was not without bias. On his deadbed, David reminded Solomon to obey the Lord, and had to take the life of Joab and Shimei (1 Kings 2:1-9), whom David himself had pardoned their lives in the past.
So was David serious about dying himself instead of his son Absalom?
The answer is "Yes". His love to his son was real and it was consistent to
his other sons, such as the dead of his firstborn Amnon, David mourned many days for his son (2 Sam 13:37). In addition, David knew it happened as a consequence of his sin, that he deeply regret but irrevocable. He tried to hide away his emotion in the chamber over the gate (2 Sam 18:33), indicate his feeling was real.