Home
DSA Patterns
Depth-First Search
Longest ZigZag Path in a Binary Tree
Longest ZigZag Path in a Binary Tree (LeetCode 1372)
Longest ZigZag Path in a Binary Tree (LeetCode 1372): find the longest path that alternates left and right steps. A DFS carries two lengths into each node: the zigzag that arrived by a left step and the one that arrived by a right step.
Problem Understanding
Longest ZigZag Path in a Binary Tree (LeetCode 1372): a zigzag path starts at any node, picks a direction (left or right), and moves to that child, then switches direction at every step until it cannot continue. Its length is the number of nodes visited minus one. Return the length of the longest zigzag path in the tree.
Examples: [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1] → 3 (right → left → right); [1,1,1,null,1,null,null,1,1,null,1] → 4 (left → right → left → right); [1] → 0.
The Intuition: Carry Both Directions Down
Every zigzag ends somewhere, arriving at its last node by either a left step or a right step. So pass two numbers down the tree: how long the zigzag is that arrives here by a left step, and by a right step.
- Start with
dfs(root, 0, 0). - At each node, update
bestwith both lengths. - Going left continues the path that arrived by a right step: the left child gets
(right + 1, 0). - Going right continues the path that arrived by a left step: the right child gets
(0, left + 1).
This is the passing values down form of DFS, like Count Good Nodes in Binary Tree, which passes the path maximum down instead.
Longest ZigZag Path in a Binary Tree Visualization
L = LENGTH ARRIVING BY A LEFT STEP · R = BY A RIGHT STEP · GREEN = BEST ZIGZAG
dfs(root, 0, 0)
left
:
right
:
best
0
call stack (root first)
No calls in progress
dfs(root 1, left = 0, right = 0): no step taken yet
Next
1: arrived with left = 0, right = 0. Best stays 0. The left child gets (0 + 1, 0); the right child gets (0, 0 + 1)
Tree
Under each visited node, L and R are the lengths it was called with. The best zigzag so far is green. Every value in LeetCode’s examples is 1, so the presets number the nodes instead; only the shape matters. Try Straight line, where no direction ever changes.
Longest ZigZag Path in a Binary Tree Dry Run
Input: LeetCode example 2’s shape, numbered: [1,2,3,null,4,null,null,5,6,null,7]. Nodes in visit order:
| Node | left | right | best |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2 | 1 | 0 | 1 |
| 4 | 0 | 2 | 2 |
| 5 | 3 | 0 | 3 |
| 7 | 0 | 4 | 4 |
| 6 | 0 | 1 | 4 |
| 3 | 0 | 1 | 4 |
The longest zigzag is 1 → 2 → 4 → 5 → 7: left, right, left, right.
Answer: 4.
Longest ZigZag Path in a Binary Tree LeetCode Solution
One DFS with two lengths as parameters and a running best.
Longest ZigZag Path in a Binary Tree Code
1var longestZigZag = function(root) {2 let best = 0;3 const dfs = (node, left, right) => {4 if (node === null) {5 return;6 }7 best = Math.max(best, left, right);8 dfs(node.left, right + 1, 0);9 dfs(node.right, 0, left + 1);10 };11 dfs(root, 0, 0);12 return best;13};
Longest ZigZag Path in a Binary Tree in Python, Java, C++, TypeScript and C
Longest ZigZag Path in a Binary Tree in Python
class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
best = 0
def dfs(node, left, right):
nonlocal best
if node is None:
return
best = max(best, left, right)
dfs(node.left, right + 1, 0)
dfs(node.right, 0, left + 1)
dfs(root, 0, 0)
return bestLongest ZigZag Path in a Binary Tree in Java
class Solution {
private int best = 0;
public int longestZigZag(TreeNode root) {
dfs(root, 0, 0);
return best;
}
private void dfs(TreeNode node, int left, int right) {
if (node == null) {
return;
}
best = Math.max(best, Math.max(left, right));
dfs(node.left, right + 1, 0);
dfs(node.right, 0, left + 1);
}
}Longest ZigZag Path in a Binary Tree in C++
class Solution {
int best = 0;
void dfs(TreeNode* node, int left, int right) {
if (node == nullptr) {
return;
}
best = max({best, left, right});
dfs(node->left, right + 1, 0);
dfs(node->right, 0, left + 1);
}
public:
int longestZigZag(TreeNode* root) {
dfs(root, 0, 0);
return best;
}
};Longest ZigZag Path in a Binary Tree in TypeScript
function longestZigZag(root: TreeNode | null): number {
let best = 0;
const dfs = (node: TreeNode | null, left: number, right: number): void => {
if (node === null) {
return;
}
best = Math.max(best, left, right);
dfs(node.left, right + 1, 0);
dfs(node.right, 0, left + 1);
};
dfs(root, 0, 0);
return best;
}Longest ZigZag Path in a Binary Tree in C
static int best;
static void dfs(struct TreeNode* node, int left, int right) {
if (node == NULL) {
return;
}
if (left > best) {
best = left;
}
if (right > best) {
best = right;
}
dfs(node->left, right + 1, 0);
dfs(node->right, 0, left + 1);
}
int longestZigZag(struct TreeNode* root) {
best = 0;
dfs(root, 0, 0);
return best;
}Edge Cases & Common Mistakes
- Counting nodes instead of edges: a single node is 0, not 1.
- Mixing up the two lengths: the left child gets
(right + 1, 0), not(left + 1, 0). A left step extends the path whose last step went right. - Only starting at the root: the longest zigzag can start anywhere; carrying both lengths down covers every start, because a broken zigzag restarts at length 1 on the next step.
- Deep trees: up to 50,000 nodes can make the recursion deep; an explicit stack avoids a stack overflow.
Summary
DFS with two lengths per node: arriving by a left step and by a right step. The left child gets (right + 1, 0), the right child (0, left + 1), and the answer is the largest length seen. O(n) time, O(h) recursion space.
More practice: DSA interview questions with answers · patterns cheat sheet
