Measurements of heavy flavor hadrons in PbPb collisions
provide information about the heavy quark dynamics inside the quark-gluon plasma (QGP). Heavy quarks are sensitive to the transport properties of the medium and may interact with the QCD matter differently from light quarks. At low $p_T$, heavy quarks provide a direct window on the in-medium QCD force. At high $p_T$, the comparison of results for light and heavy particles provides insights into the expected flavor dependence of in-medium parton energy loss. Recently, the CMS collaboration established a comprehensive heavy flavor program in heavy ion collisions including the detection of charm and beauty mesons. Using the large statistics heavy ion data samples collected
during the LHC Run 2, high precision open charm and beauty measurements are performed over a wide transverse momentum range. In this contribution, the first measurements of the radial distributions of $D^0$ mesons in jets in PbPb and pp collisions are presented, sensitive to the energy loss and diffusion of charm quarks in the QGP. Such effects for the bottom quarks are probed with the measurement of $D_0$ mesons from b-hadron decays in pp and PbPb collisions. In addition, the hadronisation of charm quarks and the importance of coalescence are constrained with the study of $\Lambda_c$ baryons in pp and PbPb collisions. Finally, results on $D_s$ and $B_s$ production are reported and compared to $D^0$ and $B^+$ production, respectively, with implications on the importance of the recombination mechanism due to strangeness enhancement.