class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if(root == nullptr) return 0;
int ans = 0;
univalue(root, &ans);
return ans;
}
private:
int univalue(TreeNode& root, int* ans) {
if(root == nullptr) return 0;
int l = univalue(root->left, ans);
int r = univalue(root->right, ans);
int pl = 0;
int pr = 0;
if(root->left && root.val == root->left.val) pl = l + 1;
if(root->left && root.val == root->right.val) pr = r + 1;
*ans = max(*ans, pr + pl);
return max(pl,pr);
}
};