Longest ZigZag Path in a Binary Tree Problem
Description
LeetCode Problem 1372.
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).
- If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
- Change the direction from right to left or from left to right.
- Repeat the second and third steps until you can't move in the tree.
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
Return the longest ZigZag path contained in that tree.
Example 1:

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).
Example 2:

Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).
Example 3:
Input: root = [1]
Output: 0
Constraints:
- The number of nodes in the tree is in the range
[1, 5 * 10^4]. 1 <= Node.val <= 100
Solution
Approach: DFS Carrying Both Directions
Starting a fresh walk from every node in both directions would visit the same subtrees again and again. Instead, do a single DFS and pass two numbers down to each node:
left: the length of the longest zigzag that ends at this node with a step to the left (we came from the parent as its left child).right: the same for a path whose last step was to the right.
When we move to a child, only one of the two can be extended:
- Going to the left child is a left step, so it continues a path whose last step was right: the child gets
left = right + 1. Itsrightvalue is0, because no path reaches it with a right step;0also stands for a brand-new path that starts at the child. - Going to the right child is symmetric: the child gets
right = left + 1andleft = 0.
The answer is the largest value seen at any node. The tricky part is the reset: a straight run (left, left) breaks the zigzag, but the second step can still start a new zigzag of length 1, and that is exactly what right + 1 with right = 0 gives.
The root starts with (0, 0), so a single node gives 0.
Complexity: O(n) time, since every node is visited once, and O(h) extra space for the recursion, where h is the height of the tree.
class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
best = 0
# left / right: length of the longest zigzag that ends at node with a left / right step.
def dfs(node: Optional[TreeNode], left: int, right: int) -> None:
nonlocal best
if node is None:
return
best = max(best, left, right)
dfs(node.left, right + 1, 0) # a left step extends a path whose last step was right
dfs(node.right, 0, left + 1) # a right step extends a path whose last step was left
dfs(root, 0, 0)
return best