Longest ZigZag Path in a Binary Tree — LeetCode 1372 Python Solution

MediumTreeDepth-First SearchDynamic ProgrammingBinary Tree
Problem
#1372
Reading time
3 min

The problem

You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: Choose any node in the binary tree and a direction (right or left).

Example

Input
root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output
3
Explanation
Longest ZigZag path in blue nodes (right -> left -> right).

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestZigZag(self, root: TreeNode) -> int:
        def dfs(root, l, r):
            if root is None:
                return
            nonlocal ans
            ans = max(ans, l, r)
            dfs(root.left, r + 1, 0)
            dfs(root.right, 0, l + 1)

        ans = 0
        dfs(root, 0, 0)
        return ans

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1372. Longest ZigZag Path in a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1372. Longest ZigZag Path in a Binary Tree?
LeetCode 1372. Longest ZigZag Path in a Binary Tree is rated Medium on LeetCode.
What topics does LeetCode 1372. Longest ZigZag Path in a Binary Tree cover?
LeetCode 1372. Longest ZigZag Path in a Binary Tree is tagged Tree, Depth-First Search, Dynamic Programming and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview