目录结构
1.题目
给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
示例:
输入:
5
/ \
4 5
/ \ \
1 1 5
输出:
2
输入:
1
/ \
4 5
/ \ \
4 4 5
输出:
2
注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-univalue-path
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
public class Solution687 {
@Test
public void test687() {
TreeNode root = new TreeNode(1, new TreeNode(4, new TreeNode(4), new TreeNode(4)),
new TreeNode(5, null, new TreeNode(5)));
System.out.println(longestUnivaluePath(root));
}
int result;
public int longestUnivaluePath(TreeNode root) {
result = 0;
getLongestUnivaluePath(root);
return result;
}
public int getLongestUnivaluePath(TreeNode node) {
if (node == null) {
return 0;
}
int left = getLongestUnivaluePath(node.left);
int right = getLongestUnivaluePath(node.right);
int currentLeft = 0, currentRight = 0;
if (node.left != null && node.left.val == node.val) {
currentLeft += left + 1;
}
if (node.right != null && node.right.val == node.val) {
currentRight += right + 1;
}
result = Math.max(result, currentLeft + currentRight);
return Math.max(currentLeft, currentRight);
}
}
- 时间复杂度:
- 空间复杂度: