Longest ZigZag Path in a Binary Tree - Problem

You are given the root of a binary tree.

A ZigZag path for a binary tree is defined as follows:

  • 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

The zigzag length is defined as the number of nodes visited minus 1. (A single node has a length of 0).

Return the longest ZigZag path contained in that tree.

Input & Output

Example 1 — Complex Tree
$ Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]
Output: 3
💡 Note: The longest ZigZag path has length 3. Starting from the right child of root, go Left→Right→Left to reach maximum length.
Example 2 — Simple Path
$ Input: root = [1,1,1,null,1,null,null,1,1,null,1]
Output: 4
💡 Note: The longest ZigZag path goes Right→Left→Right→Left→Right, giving length 4.
Example 3 — Single Node
$ Input: root = [1]
Output: 0
💡 Note: A single node has zigzag length 0 by definition.

Constraints

  • The number of nodes in the tree is in the range [1, 5 × 104]
  • 1 ≤ Node.val ≤ 100

Visualization

Tap to expand
Longest ZigZag Path in Binary Tree INPUT 1 1 1 1 1 1 1 1 [1,null,1,1,1,null,null,1,1...] ALGORITHM STEPS 1 DFS Traversal Visit each node recursively 2 Track Direction Pass left/right state to child 3 Alternate Path Extend if direction changes 4 Update Maximum Track longest path found ZigZag Path Example R 1 2 Right Left Right... FINAL RESULT Longest ZigZag Path 1 1 1 1 1 R L R L Output 3 OK - Path length = 3 (4 nodes, 3 edges) Key Insight: At each node, track TWO values: the longest zigzag ending with a LEFT move, and with a RIGHT move. When going left, extend the "came from right" path. When going right, extend "came from left" path. Reset the other direction to 1 (starting fresh). Update global max at each node. Time: O(n), Space: O(h) TutorialsPoint - Longest ZigZag Path in a Binary Tree | DFS with State Tracking
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
89.2K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen