Problem summary: You are given the root of a binary tree. A ZigZag path for a binary tree is defined as follow: 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. Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0). Return the longest ZigZag path contained in that tree.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Zigzag Grid Traversal With Skip (zigzag-grid-traversal-with-skip)
Step 02
Core Insight
What unlocks the optimal approach
Create this function maxZigZag(node, direction) maximum zigzag given a node and direction (right or left).
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1372: Longest ZigZag Path in a Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans;
public int longestZigZag(TreeNode root) {
dfs(root, 0, 0);
return ans;
}
private void dfs(TreeNode root, int l, int r) {
if (root == null) {
return;
}
ans = Math.max(ans, Math.max(l, r));
dfs(root.left, r + 1, 0);
dfs(root.right, 0, l + 1);
}
}
// Accepted solution for LeetCode #1372: Longest ZigZag Path in a Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func longestZigZag(root *TreeNode) int {
ans := 0
var dfs func(root *TreeNode, l, r int)
dfs = func(root *TreeNode, l, r int) {
if root == nil {
return
}
ans = max(ans, max(l, r))
dfs(root.Left, r+1, 0)
dfs(root.Right, 0, l+1)
}
dfs(root, 0, 0)
return ans
}
# Accepted solution for LeetCode #1372: Longest ZigZag Path in a Binary Tree
# Definition for a binary tree node.
# 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: TreeNode) -> int:
def dfs(root, l, r):
if root is None:
return
nonlocal ans
ans = max(ans, l, r)
dfs(root.left, r + 1, 0)
dfs(root.right, 0, l + 1)
ans = 0
dfs(root, 0, 0)
return ans
// Accepted solution for LeetCode #1372: Longest ZigZag Path in a Binary Tree
struct Solution;
use rustgym_util::*;
trait Postorder {
fn postorder(&self, max: &mut i32) -> (i32, i32);
}
impl Postorder for TreeLink {
fn postorder(&self, max: &mut i32) -> (i32, i32) {
if let Some(node) = self {
let node = node.borrow();
let (_, left_right) = node.left.postorder(max);
let (right_left, _) = node.right.postorder(max);
let left = left_right + 1;
let right = right_left + 1;
*max = (*max).max(left);
*max = (*max).max(right);
(left, right)
} else {
(0, 0)
}
}
}
impl Solution {
fn longest_zig_zag(root: TreeLink) -> i32 {
let mut res = 0;
root.postorder(&mut res);
res - 1
}
}
#[test]
fn test() {
let root = tree!(
1,
None,
tree!(
1,
tree!(1),
tree!(1, tree!(1, None, tree!(1, None, tree!(1))), tree!(1))
)
);
let res = 3;
assert_eq!(Solution::longest_zig_zag(root), res);
let root = tree!(
1,
tree!(1, None, tree!(1, tree!(1, None, tree!(1)), tree!(1))),
tree!(1)
);
let res = 4;
assert_eq!(Solution::longest_zig_zag(root), res);
let root = tree!(1);
let res = 0;
assert_eq!(Solution::longest_zig_zag(root), res);
}
// Accepted solution for LeetCode #1372: Longest ZigZag Path in a Binary Tree
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1372: Longest ZigZag Path in a Binary Tree
// /**
// * Definition for a binary tree node.
// * public class TreeNode {
// * int val;
// * TreeNode left;
// * TreeNode right;
// * TreeNode() {}
// * TreeNode(int val) { this.val = val; }
// * TreeNode(int val, TreeNode left, TreeNode right) {
// * this.val = val;
// * this.left = left;
// * this.right = right;
// * }
// * }
// */
// class Solution {
// private int ans;
//
// public int longestZigZag(TreeNode root) {
// dfs(root, 0, 0);
// return ans;
// }
//
// private void dfs(TreeNode root, int l, int r) {
// if (root == null) {
// return;
// }
// ans = Math.max(ans, Math.max(l, r));
// dfs(root.left, r + 1, 0);
// dfs(root.right, 0, l + 1);
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.