Longest ZigZag Path in a Binary Tree (LeetCode 1372): Solution and Explanation
A zigzag path alternates left and right moves down a binary tree. Return the number of moves in the longest one, starting from any node.
Intuition
Starting a walk from every node and following it down would repeat a lot of work. Flip the view around: instead of asking where a zigzag goes, ask how it can end at a given node.
A path can end at a node by a left move (the node is a left child) or by a right move (it is a right child). Call those lengths left and right. If the node is a left child, the move before it must have been a right move into the parent, so left = parent.right + 1, and right = 0 because a right move cannot end here.
The same rule mirrored gives right = parent.left + 1 for a right child. So one pass from the root down fills in both numbers for every node, and the answer is the largest number seen anywhere.
Approach: DFS carrying (left, right) lengths
- Push (root, 0, 0) onto a stack and set best = 0.
- Pop (node, left, right) and set best = max(best, left, right).
- If the node has a left child, push it with (right + 1, 0): the turn extends the path that ended with a right move.
- If the node has a right child, push it with (0, left + 1).
- When the stack is empty, return best.
Step-by-step example
root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
- The root has (0, 0). It has only a right child, which gets (0, 0 + 1) = (0, 1).
- That node, A, has two children: its left child gets (1 + 1, 0) = (2, 0) and its right child gets (0, 1).
- A's left child is a leaf with left = 2, so best becomes 2.
- A's right child B has (0, 1). B's left child C gets (2, 0); B's right child gets (0, 1).
- C's right child gets (0, 2 + 1) = (0, 3), so best becomes 3: right, right, left, right from the root, or three moves starting at A. No node scores higher, so the answer is 3.
Code: Python, Java, C++
1class Solution:
2 def longestZigZag(self, root: Optional[TreeNode]) -> int:
3 best = 0
4 stack = [(root, 0, 0)]
5 while stack:
6 node, left, right = stack.pop()
7 best = max(best, left, right)
8 if node.left:
9 stack.append((node.left, right + 1, 0))
10 if node.right:
11 stack.append((node.right, 0, left + 1))
12 return best1class Solution {
2 public int longestZigZag(TreeNode root) {
3 int best = 0;
4 Deque<TreeNode> nodes = new ArrayDeque<>();
5 Deque<int[]> lens = new ArrayDeque<>();
6 nodes.push(root);
7 lens.push(new int[]{0, 0});
8 while (!nodes.isEmpty()) {
9 TreeNode node = nodes.pop();
10 int[] lr = lens.pop();
11 best = Math.max(best, Math.max(lr[0], lr[1]));
12 if (node.left != null) {
13 nodes.push(node.left);
14 lens.push(new int[]{lr[1] + 1, 0});
15 }
16 if (node.right != null) {
17 nodes.push(node.right);
18 lens.push(new int[]{0, lr[0] + 1});
19 }
20 }
21 return best;
22 }
23}1class Solution {
2public:
3 int longestZigZag(TreeNode* root) {
4 struct Item { TreeNode* node; int left; int right; };
5 int best = 0;
6 vector<Item> stack = {{root, 0, 0}};
7 while (!stack.empty()) {
8 Item it = stack.back();
9 stack.pop_back();
10 best = max(best, max(it.left, it.right));
11 if (it.node->left) stack.push_back({it.node->left, it.right + 1, 0});
12 if (it.node->right) stack.push_back({it.node->right, 0, it.left + 1});
13 }
14 return best;
15 }
16};Time and space complexity
O(n)
Every node is pushed and popped once with constant work.
O(n)
The explicit stack holds pending nodes; for a DFS it is bounded by the height plus waiting siblings, which is O(n) for a degenerate tree.
Other approaches
Recursive DFS with a direction flag (time O(n), space O(h))
Call dfs(node, cameFromLeft, length): the child in the turning direction gets length + 1, the child in the same direction restarts at 1. Same logic, but deep chains can overflow the call stack.
Postorder returning two values (time O(n), space O(h))
Each node returns the longest zigzag that starts at it going left and going right: goLeft = 1 + left.goRight, goRight = 1 + right.goLeft. Track the maximum over all nodes.
Common mistakes
- Counting nodes instead of moves. A single node is length 0, so the answer is one less than the number of nodes on the path.
- Resetting to 0 when the path goes straight. Going the same direction twice starts a new zigzag of length 1 at the child, not 0.
- Only starting from the root. The best zigzag can begin anywhere, which the restart-at-1 rule handles automatically.
Frequently asked questions
Why does every non-root node have one of its two numbers equal to 0?
A node is either a left child or a right child, so a path can reach it by only one kind of move. The other kind of ending is impossible and stays 0.
Where do paths that start in the middle of the tree come from?
When a child goes in the same direction as its parent's last move, its count restarts at 1. That is exactly a new zigzag beginning at the parent.
Why use an explicit stack?
The tree can have 50,000 nodes in a single chain. Recursion that deep overflows the default call stack in Python and can in other languages, while an explicit stack has no such limit.