Longest Univalue Path

Given the root of a binary tree, return the length of the longest path where every node in the path has the same value. The path may pass through the root or stay entirely in one subtree. Pattern focus: Postorder DFS (Left Right Root). Compute the best extension from each child before combining at the parent.

Input Format

root = binary tree root

Output Format

length of the longest same-value path in number of edges

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^4 <= node values <= 10^4
  • Input must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

root = [5,4,5,1,1,null,5]

Output:

2

Explanation:

The longest univalue path has two edges with value 5.

Example 2:

Input:

root = [1,4,5,4,4,null,5]

Output:

2

Explanation:

The longest chain of equal values has length 2 edges.

Loading...
Longest Univalue Path - Binary Tree DSA Problem