Longest ZigZag Path in a Binary Tree - Problem
The ZigZag Path Adventure
You are given the root of a binary tree and need to find the longest possible ZigZag path.
A ZigZag path in a binary tree follows these rules:
• Start at any node in the tree and choose a direction (left or right)
• At each step, alternate the direction: if you went right, next go left (and vice versa)
• Continue until you can't move further in the required direction
The ZigZag length is the number of edges traversed (nodes visited - 1).
Goal: Return the length of the longest ZigZag path in the entire tree.
You are given the root of a binary tree and need to find the longest possible ZigZag path.
A ZigZag path in a binary tree follows these rules:
• Start at any node in the tree and choose a direction (left or right)
• At each step, alternate the direction: if you went right, next go left (and vice versa)
• Continue until you can't move further in the required direction
The ZigZag length is the number of edges traversed (nodes visited - 1).
Goal: Return the length of the longest ZigZag path in the entire tree.
Example: A path going Right → Left → Right → Left has length 3. Input & Output
example_1.py — Basic Zigzag Tree
$
Input:
root = [1,null,1,1,1,null,null,1,1,null,1]
›
Output:
3
💡 Note:
The longest zigzag path is: right -> left -> right -> left, starting from the root and following the path 1->1->1->1 with length 3.
example_2.py — Simple Tree
$
Input:
root = [1,1,1,null,1,null,null,1,1,null,1]
›
Output:
4
💡 Note:
The longest zigzag path has length 4, following a path that alternates directions optimally through the tree structure.
example_3.py — Single Node
$
Input:
root = [1]
›
Output:
0
💡 Note:
A tree with only one node has no edges, so the zigzag length is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Start DFS Traversal
Begin exploring from root, trying both left and right directions
2
Track Path States
At each node, remember the longest left-ending and right-ending zigzag paths
3
Extend or Reset
When moving to child: extend current zigzag or start fresh
4
Find Maximum
Keep track of the longest zigzag path discovered during traversal
Key Takeaway
🎯 Key Insight: Use DFS to track both left-ending and right-ending zigzag lengths at each node, building the optimal solution in a single pass.
Time & Space Complexity
Time Complexity
O(n)
Single traversal visiting each node exactly once
✓ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h
✓ Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 5 × 104]
- -100 ≤ Node.val ≤ 100
- Each node contains an integer value and left/right pointers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code