hardTreesPure DSA~35 min
Longest Path of Equal-Valued Nodes
Find the longest path in a tree along which every node shares the same value (label). The path may bend through a node, joining one branch to another.
Problem
Given the root of a binary tree, return the length of the longest path where all nodes have the same value. The length is the number of edges on the path; the path need not pass through the root.
Input
A binary tree root with integer node values.
Output
An integer: the longest equal-value path length in edges.
Constraints
- 0 <= number of nodes <= 10^4
- -1000 <= node value <= 1000
- Tree depth fits the recursion stack.
Examples
Example 1
Input
root = [5,4,5,1,1,null,5]
Output
2
The path 5 -> 5 -> 5 through the root has length 2.
Example 2
Input
root = [1,4,5,4,4,null,5]
Output
2
The path 4 -> 4 -> 4 has length 2.