← 返回 snowflake 的题目列表Longest Univalue Path
类型:qbank
Given the root of a binary tree, return the length of the longest path where each node in the path has the same value.
Longest Univalue Path
Given the root of a binary tree, return the length of the longest path where each node in the path has the same value.
SWE
tree
dfs
recursion
medium
Frequency
Single report
Last asked
2025-12-23
Stage
phone-screen · onsite-coding
Longest Univalue Path
Problem Explanation
You are provided with the root of a binary tree. Your task is to find the length of the longest path in the tree where every node in that path shares the exact same value.
Here are a few rules to keep in mind:
The path does not have to go through the root. It can start and end anywhere in the tree.
The length is measured by the number of edges (connections) between nodes, not the count of nodes themselves.
Test Cases
Case 1:
Input: root = [5,4,5,1,1,null,5]
Output: 2
Case 2:
Input: root = [1,4,5,4,4,null,5]
Output: 2
Input Limits
Tree Size: The number of nodes is between 0 and 10^4.
Node Values: Each Node.val is between -1000 and 1000.