InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Longest ZigZag Path in a Binary Tree

medium Original ↗ 00:00

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 at any point.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug