dfs(node)
that returns the length of the longest path starting from node
and consisting of nodes with the same value as node
.node
is null
, return 0.dfs(node.left)
and dfs(node.right)
to get the longest paths for the left and right subtrees.node.left
is not null
and has the same value as node
, include the left path in the current path length. Otherwise, set the left path length to 0.node.right
is not null
and has the same value as node
, include the right path in the current path length. Otherwise, set the right path length to 0.dfs(root)
and return the global maximum path length.