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

Longest Same-Value Path

binary tree · recursion · post-order

Return the number of edges on the longest path in which every node has the same value. The path may bend at one node (going down into both children) and does not need to pass through the root. An empty tree or a single node gives 0.

Examples

      5
     / \
    4   5
   / \   \
  1   1   5

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

Input:  root = build_tree([1, 4, 5, 4, 4, None, 5])
Output: 2
Explanation: 4 -> 4 -> 4 bends at the node 4 on the left.

Goals

  • Return the best single arm to the parent while recording the best two-arm path globally
  • Compare a child's value with its parent's before extending a run
Starting Python…