Longest ZigZag Path in a Binary Tree
Hard
Topics
A ZigZag path alternates direction (left, right, left, ...) at each step. Its length is the number of edges visited. Given the root of a binary tree, return the length of the longest ZigZag path contained in it.
Example 1
null marks a missing child.Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] Output: 3
Example 2
Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4
Example 3
Input: root = [1] Output: 0
Constraints
- 1 <= number of nodes <= 5*10^4
- 1 <= Node.val <= 100.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A zigzag path is determined by where it starts and which way it first turns, and from then on every step is forced. So each node needs two numbers: the longest zigzag that leaves it going left, and the longest that leaves it going right.
Those compose upward. Going left from a node means stepping into the left child and then that child must go right, so the node's left-value is its left child's right-value plus one. Symmetrically for the right. A post-order traversal computes both in one pass, and the answer is the largest value seen anywhere — not the root's, since the best path need not start at the root.
The base case is the trick: a missing child returns -1, so a leaf computes -1 + 1 = 0 for both directions, correctly saying a leaf has a zigzag of zero edges.
Approach
- Recurse post-order, returning a pair
(goLeft, goRight)per node. - A null node returns
(-1, -1). goLeft = leftChild.goRight + 1andgoRight = rightChild.goLeft + 1.- Fold both into a running maximum.
- Return the running maximum, not the root's pair.
Dry Run
tree: root, then right, then left, then right -- a perfect zigzag
1
1
/
1
1
node returns (goLeft, goRight)
bottom leaf (0, 0) both children null: -1 + 1
its parent (0, 1) goRight = leaf.goLeft + 1 = 1
next up (2, 0) goLeft = child.goRight + 1 = 2
root (0, 3) goRight = child.goLeft + 1 = 3
answer 3 edges
a straight left chain of 10 nodes answers 1: there is no alternation to extendComplexity
- Time — O(n): one visit per node, constant work each.
- Space — O(h) for the call stack. At the stated bound of 5×10⁴ nodes a degenerate path needs 50,000 frames, which exceeds Python's default limit of 1,000 and Java's default thread stack of roughly 20,000, and far exceeds Node's. The Python harness on this page raises the limit; an explicit stack is the portable fix.
Common Pitfalls
- Returning the root's pair instead of the global maximum. The longest zigzag can start at any node.
- Pairing a direction with itself —
goLeft = leftChild.goLeft + 1. That measures a straight chain, not a zigzag, and makes a left-leaning path answer its depth. - Using 0 as the null base case, which makes every leaf report 1 and inflates the answer by one.
- Counting nodes instead of edges. A single node is 0, not 1 — the problem defines length as edges visited.
- Passing the direction downward and recomputing from each node independently. That is O(n²) without memoisation; the post-order pair is what makes it linear.
- Treating the two values as interchangeable in the parent. The cross-over — left uses the child's right — is the entire content of the recurrence.
Full Solution — all languages
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):
self.best = 0
def dfs(node):
if not node: return (-1, -1)
l = dfs(node.left); r = dfs(node.right)
left = l[1] + 1; right = r[0] + 1
if left > self.best: self.best = left
if right > self.best: self.best = right
return (left, right)
if root: dfs(root)
return self.bestimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int longestZigZag(TreeNode root) {
best = 0;
if (root != null) dfs(root);
return best;
}
int best;
private int[] dfs(TreeNode node) {
if (node == null) return new int[]{-1, -1};
int[] l = dfs(node.left), r = dfs(node.right);
int left = l[1] + 1, right = r[0] + 1;
if (left > best) best = left;
if (right > best) best = right;
return new int[]{left, right};
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int longestZigZag(TreeNode* root) {
int best = 0;
function<array<int,2>(TreeNode*)> dfs = [&](TreeNode* node) -> array<int,2> {
if (!node) return {
-1, -1
};
array<int,2> l = dfs(node->left), r = dfs(node->right);
int left = l[1] + 1, right = r[0] + 1;
if (left > best) best = left;
if (right > best) best = right;
return {
left, right
};
};
if (root) dfs(root);
return best;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var longestZigZag = function(root) {
let best = 0;
const dfs = (node) => {
if (!node) return [-1, -1];
const l = dfs(node.left), r = dfs(node.right);
const left = l[1] + 1, right = r[0] + 1;
if (left > best) best = left;
if (right > best) best = right;
return [left, right];
};
if (root) dfs(root);
return best;
};