Longest ZigZag Path in a Binary Tree

Hard

Topics
TreeDFSDynamic Programming

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

111111111
A zigzag path must alternate direction at every step, so each node needs two numbers: the best run arriving from the left and from the right. Going left continues the child’s right-run and vice versa. The shaded path has 3 edges.
Tree given in level-order (breadth-first); 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

1111111
Input:  root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4

Example 3

1
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

  1. Recurse post-order, returning a pair (goLeft, goRight) per node.
  2. A null node returns (-1, -1).
  3. goLeft = leftChild.goRight + 1 and goRight = rightChild.goLeft + 1.
  4. Fold both into a running maximum.
  5. 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 extend

Complexity

  • 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.best
SensAI
Beta
Tap the mic to stop voice mode