题目
给定一个二叉树的 root ,返回 最长的路径的长度 ,这个路径中的 每个节点具有相同值 。 这条路径可以经过也可以不经过根节点。
两个节点之间的路径长度 由它们之间的边数表示。
- 来源:力扣(LeetCode)
- 链接:leetcode.cn/problems/lo…
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
思路
代码
class Solution {
private int max = 0;
public int longestUnivaluePath(TreeNode root) {
helper(root);
return max;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
int leftPath = 0;
if (root.left != null && root.val == root.left.val) {
leftPath = left + 1;
}
int rightPath = 0;
if (root.right != null && root.val == root.right.val) {
rightPath = right + 1;
}
max = Math.max(max, leftPath + rightPath);
return Math.max(leftPath, rightPath);
}
}
复杂度
- 时间复杂度:O(N)
- 空间复杂度:O(H) H表示树高