#K9401. 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 of the longest path in which every node in the path has the same value. This path can be either entirely in the left subtree, right subtree, or may pass through the root. The length of the path is determined by the number of edges between the nodes.
Note: A single node has a path length of 0.
Definition: For a tree node \( root \), a univalue path is defined as a path where every node has the same value. The answer is the maximum number of edges in any such path in the tree.
Example 1:
Input: 5 4 5 1 1 null 5
Output: 2
Example 2:
Input: 1 4 5 4 4 null 5
Output: 2
inputFormat
The input is given via standard input (stdin) as a single line.
The line contains the level-order traversal of the binary tree where each value is separated by a space. Use the token null
(or N
) to represent an empty node.
Example: 5 4 5 1 1 null 5
outputFormat
Output via standard output (stdout) a single integer representing the length of the longest univalue path (i.e., the number of edges in that path).
## sample5 4 5 1 1 null 5
2