0687. Longest Univalue Path
Last updated
Last updated
**Input:** root = [5,4,5,1,1,5]
**Output:** 2**Input:** root = [1,4,5,4,4,5]
**Output:** 2/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max;
public int longestUnivaluePath(TreeNode root) {
max = 0;
unilateralLen(root);
return max;
}
private int unilateralLen(TreeNode root) {
// exit
if (root == null) return 0;
int left = unilateralLen(root.left);
int right = unilateralLen(root.right);
int l = root.left != null && root.val == root.left.val ? left + 1 : 0;
int r = root.right != null && root.val == root.right.val ? right + 1 : 0;
max = Math.max(max, l + r); // update max
return Math.max(l, r);
}
}