children
to store the children of each node.longestPath
to 1, as a single node is always a valid path.dfs
function that takes the current node, its children, the string s
, and the longestPath
as parameters and returns the length of the longest chain starting from the current node.dfs
function, initialize longestChain
and secondLongestChain
to 0.dfs
recursively, and update longestChain
and secondLongestChain
accordingly.longestPath
with the sum of longestChain
, secondLongestChain
, and 1 (for the current node).longestChain + 1
to include the current node in the chain.longestPath
as the final answer.