MediumNo. 1372

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

Topics
Tree, Depth-First Search, Dynamic Programming, Binary Tree
On a study list
LeetCode 75
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

PythonSolution
# 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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

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.

Free to download. Check it runs on your machine, then pick a plan.