InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Longest ZigZag Path in a Binary Tree

medium Original ↗
Solving tips
  • This is tree DP with two states per node: track down_left and down_right (longest zigzag starting by going left vs right), computed bottom-up in one post-order pass.
  • The direction flips across each edge: down_left(node) = 1 + down_right(node.left) and down_right(node) = 1 + down_left(node.right) — using the child's same-direction run computes a straight path, not a zigzag.
  • Keep a running global max of max(down_left, down_right) at every node; the answer is not just the root's value. Target O(n) time, O(h) space.
  • Pitfall: length is EDGES not nodes (a leaf is 0); returning -1 for a null child makes 1+(-1)=0 handle missing children cleanly.

Problem

You are given the root of a binary tree. A zigzag path is defined by:

  • Start at any node and choose a direction, left or right.
  • Move to that child, then flip the direction for the next move (left → right → left → …).
  • Stop whenever you like.

The length of a zigzag path is the number of edges it traverses (a single node with no moves has length 0). Return the length of the longest zigzag path anywhere in the tree.

Examples

  • Tree [1, null, 1, 1, 1, null, null, 1, 1, null, 1, null, null, null, 1]3 — the longest alternating right-left-right-left chain uses 3 edges.
  • A single node → 0 — no edges to traverse.
  • A straight left-left-left chain of 4 nodes → 1 — after the first left move you must go right; there is no right child, so the zigzag stops at 1 edge.

Constraints

  • The number of nodes is in [1, 5 * 10^4].
  • 1 <= Node.val <= 100.

With up to 50,000 nodes, the expected solution is a single O(n) traversal.

Think about it first

Hint 1 For any node, a zigzag that continues *downward through it* is characterized by which direction it leaves the node: "go left, then zigzag" or "go right, then zigzag." Those are two independent quantities to track at every node.
Hint 2 Think bottom-up. If you know, for a node's left child, how long the best "start by going right" zigzag is, then this node's "go left" path is `1 + (that value)` — because after stepping left into the child, the zigzag must turn right. Two states per node — call it a 2-D DP where the second dimension is {left, right}.
Hint 3 Post-order DFS returning `(down_left, down_right)` for each node: `down_left = 1 + down_right(node.left)` and `down_right = 1 + down_left(node.right)` (0 if the child is missing). Update a global maximum with `max(down_left, down_right)` at every node.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.