Longest ZigZag Path in Binary Tree

Medium

Description

A ZigZag path alternates between going left and right child. Given the root, return the length of the longest ZigZag path.

Examples

Input:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
Output:3
Explanation:

Zigzag of length 3.

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

The longest zigzag path starts from the root, goes left to node 1, then right to node 1, then left to node 1, then right to node 1. This creates a zigzag pattern of length 4: root → left → right → left → right.

Input:root = [1]
Output:0
Explanation:

A single node tree has no edges to traverse, so the longest zigzag path has length 0. There are no left or right moves possible from the root.

Constraints

  • 1 ≤ nodes ≤ 5 × 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!