class Solution {
int max = 0;
public int longestUnivaluePath(TreeNode root) {
if(root == null) return 0;
dfs(root);
return max;
}
public int dfs(TreeNode root){
if(root.left == null && root.right == null) return 0;
int left = root.left != null ? dfs(root.left) + 1 : 0;
int right = root.right != null ? dfs(root.right) + 1 : 0;
// 若当前节点和左/右孩子节点不同值,则重置为0
if(left > 0 && root.left.val != root.val) left = 0;
if(right > 0 && root.right.val != root.val) right = 0;
max = Math.max(max, left + right);
return Math.max(left, right);
}
}
687.最长同值路径 双百0ms
最新推荐文章于 2025-12-09 14:04:42 发布
本文介绍了一种求解二叉树中最长相同值路径的算法实现。通过深度优先搜索(DFS)策略,递归地计算每个节点的左右子树中相同值的最长路径长度,并更新全局最大值。
1247

被折叠的 条评论
为什么被折叠?



