That's exactly how it should be done! Also subtle but important that you find the last closing parentheses, as an attacker could just include a paren in their process name to terminate your parse early.
https://gitlab.com/psmisc/psmisc/-/blob/master/src/pstree.c#...