```java
class Solution {
int result = 0;
public int longestUnivaluePath(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root, root.val);
return result;
}
private int dfs(TreeNode node, int prev) {
if (node == null) {
return 0;
}
int left = dfs(node.left, node.val);
int right = dfs(node.right, node.val);
result = Math.max(result, left + right);
if (node.val == prev) {
return Math.max(left, right) + 1;
}
return 0; // node.val != prev
}
}
```
class Solution {
int res = 0;
public int longestUnivaluePath(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root);
return res-1;
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int len1 = dfs(root.left);
int len2 = dfs(root.right);
int left = 0;
int right = 0;
if (root.left != null && root.val == root.left.val) {
left = len1;
}
if (root.right != null && root.val == root.right.val) {
right = len2;
}
res = Math.max(res, left+right+1);
return Math.max(left, right)+1;
}
}