SDE & MLE Prep

1372. Longest ZigZag Path in a Binary Tree

Problem

A zigzag path starts at any node, picks a direction (left or right), and alternates direction at every step down. Return the length (in edges) of the longest zigzag path.

Example: [1,1,1,null,1,null,null,1,1,null,1] → 4

Constraints: up to 5·10⁴ nodes.

For every node compute two values: the longest zigzag starting here going left (= 1 + the left child's "going right" value) and going right (= 1 + the right child's "going left"). A missing child contributes −1 so the step to it counts 0. The answer is the maximum over all nodes.

Complexity: O(n).

class Solution:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:
        best = 0

        def dfs(node):                       # -> (zigzag length going left, going right), in edges
            nonlocal best
            if not node:
                return -1, -1
            left = dfs(node.left)[1] + 1
            right = dfs(node.right)[0] + 1
            best = max(best, left, right)
            return left, right

        dfs(root)
        return best