Longest ZigZag Path in a Binary Tree - Problem

You are given the root of a binary tree.

A ZigZag path for a binary tree is defined as follows:

  • 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

The zigzag length is defined as the number of nodes visited minus 1. (A single node has a length of 0).

Return the longest ZigZag path contained in that tree.

Input & Output

Example 1 — Complex Tree
$ Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output: 3
💡 Note: The longest ZigZag path has length 3. Starting from the right child of root, go Left→Right→Left to reach maximum length.
Example 2 — Simple Path
$ Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
💡 Note: The longest ZigZag path goes Right→Left→Right→Left→Right, giving length 4.
Example 3 — Single Node
$ Input: root = [1]
Output: 0
💡 Note: A single node has zigzag length 0 by definition.

Constraints

  • The number of nodes in the tree is in the range [1, 5 × 104]
  • 1 ≤ Node.val ≤ 100

Visualization

Tap to expand
Longest ZigZag Path in Binary Tree1111111RightLeftRightZigZag: Right → Left → Right (Length = 3)Output: 3
Understanding the Visualization
1
Input Tree
Binary tree with nodes where we need to find zigzag paths
2
ZigZag Paths
Alternate between left and right moves at each step
3
Maximum Length
Return the length of the longest zigzag path found
Key Takeaway
🎯 Key Insight: Use DFS to track both left-going and right-going zigzag paths at each node simultaneously
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
89.2K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen