#C12139. Longest Univalue Path in a Binary Tree
Longest Univalue Path in a Binary Tree
Longest Univalue Path in a Binary Tree
Given a binary tree, find the length (number of edges) of the longest path where every node in the path has the same value. The path does not necessarily have to pass through the root.
Formally, let the tree be represented as \(T\). A path is defined as a sequence of nodes \(n_0, n_1, \dots, n_k\) such that each pair of adjacent nodes are connected by an edge and \(n_i \ne n_j\) for \(i \ne j\). The length of the path is \(k\) (i.e. the number of edges). In this problem, we require that for every adjacent pair \((n_i, n_{i+1})\), the equality \(n_i.val = n_{i+1}.val\) holds.
Your task is to output the length of such a longest univalue path. If no such path exists (i.e. if the tree has no edge connecting nodes of the same value), output 0.
Note: The number of nodes is at most \(10^4\) and node values are integers.
inputFormat
The input is a single line containing a level-order representation of the binary tree as a list. The list is given in the format of [v1,v2,...,vn]
, where each value is either an integer or the literal null
(which represents the absence of a node).
For example, the input [1,4,5,4,4,null,5]
corresponds to the following tree:
1 / \ 4 5 / \ \ 4 4 5
outputFormat
Output a single integer representing the length of the longest univalue path in the tree (i.e. the maximum number of edges connecting nodes with the same value).
## sample[1,4,5,4,4,null,5]
2