max_length
to store the maximum ZigZag path length found so far.dfs(node, direction, length)
where node
is the current tree node, direction
is a boolean indicating whether to go left (true) or right (false), and length
is the current ZigZag path length.null
, return from the function.max_length
with the maximum of its current value and length
.direction
is true, recursively call dfs(node.left, false, length + 1)
to continue the ZigZag path to the left, and dfs(node.right, true, 1)
to start a new path to the right.direction
is false, recursively call dfs(node.right, true, length + 1)
to continue the ZigZag path to the right, and dfs(node.left, false, 1)
to start a new path to the left.dfs(root, true, 0)
and dfs(root, false, 0)
.max_length
as the result.