AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Longest ZigZag Path in a Binary Tree

The key idea

At every node, the best zigzag that turns LEFT here equals one more edge than the best zigzag that turns RIGHT at its left child (and symmetrically for turning right). So a single post-order DFS can return, for each node, the two values (go-left length, go-right length) built from its children, while a global maximum records the best path seen anywhere.

Problem

You are given the root of a binary tree. A ZigZag path is built by choosing any starting node and an initial direction (left or right), moving to the corresponding child, then alternating direction at every step: if you just moved right you must next move left, and if you just moved left you must next move right. You keep moving until there is no child in the required direction. The length of a ZigZag path is the number of edges it uses, which is the number of visited nodes minus 1 (a single node has length 0). Return the length of the longest ZigZag path contained in the tree.

Constraints

Examples

Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] Output: 3
Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4
Input: root = [1] Output: 0

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems