Problem 410094 · medium · Level 04 Non-Linear Data Structures

Longest Alternating Descent

binary tree · recursion · dynamic programming

A zigzag descent starts at any node and repeatedly moves to a child, but the direction must alternate: after moving to a left child the next move must go to a right child, and vice versa. Its length is the number of edges used. Return the length of the longest zigzag descent in the tree (0 for a single node or an empty tree).

Examples

    1
   / \
  2   3
   \
    4
   /
  5

Input:  root = build_tree([1, 2, 3, None, 4, None, None, 5])
Output: 3
Explanation: 1 -> 2 (left) -> 4 (right) -> 5 (left).

Input:  root = build_tree([1, 1, 1, 1, 1, 1, 1])
Output: 2

Constraints

  • 0 <= number of nodes <= 1000

Goals

  • Pass direction-dependent state down the tree
  • Reset one counter while extending the other
Starting Python…