树的最长路径代表的意思是树的两个结点之间的边的条数,
刚开始我理解错题目的意思了,以为求的是最多联通的结点数。
比如说这组数据:[ 1,null,1,1,1,1,1,1,null,1]
它的最长路径见下图:
class Solution {
public :
int ans = 0 ;
int longestUnivaluePath ( TreeNode* root) {
solve ( root) ;
return ans;
}
int solve ( TreeNode * root) {
if ( root == nullptr ) return 0 ;
int l = solve ( root- > left) ;
int r = solve ( root- > right) ;
int templ = 0 , tempr = 0 ;
if ( root- > left != nullptr && root- > left- > val == root- > val) {
templ = l + 1 ;
}
if ( root- > right != nullptr && root- > right- > val == root- > val) {
tempr = r + 1 ;
}
ans = max ( ans, templ + tempr) ;
return max ( templ, tempr) ;
}
} ;
我最开始理解的代码
class Solution {
public :
int ans = 0 ;
int longestUnivaluePath ( TreeNode* root) {
solve ( root) ;
return ans;
}
int solve ( TreeNode * root) {
if ( root == nullptr ) return 0 ;
int l = solve ( root- > left) ;
int r = solve ( root- > right) ;
int templ = 0 , tempr = 0 ;
if ( root- > left != nullptr && root- > left- > val == root- > val) {
templ = l + 1 ;
}
if ( root- > right != nullptr && root- > right- > val == root- > val) {
tempr = r + 1 ;
}
ans = max ( ans, templ + tempr) ;
return templ + tempr;
}
} ;