Problem 610
Longest ZigZag Path in a Binary Tree
Medium · 20 pts · Tree, Depth-First Search, Dynamic Programming
Problem
A zigzag path starts at any node, picks a direction (left or right), moves to that child, then switches direction at every step: left, right, left, ... or right, left, right, .... It stops when the next child does not exist. Its length is the number of edges travelled, so a single node gives 0. Find the longest zigzag path in the tree. For each node track the longest zigzag ending there whose last move was left, and the one whose last move was right.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the length of the longest zigzag path.
Constraints
1 <= number of nodes <= 10000; 1 <= value <= 100
Example input
11 1 1 1 null 1 null null 1 1 null 1
Example output
4
Explanation
In the tree 1 1 1 null 1 null null 1 1 null 1, start at the root and go left, right, left, right. That zigzag has 4 edges, and no longer one exists.