4
pair<int, int> util(TreeNode *root, int val) {5
if (!root) return {0, -1001};7
// in pair we will the first part will return the no nodes ,8
// and in the second part we will return the value associated with it10
pair<int, int> l = util(root->left, root->val);11
pair<int, int> r = util(root->right, root->val);13
/* now we will check whether the value coming from14
the left subtree or(&) right subtree is equal to the15
value of the current node17
if equal to both the left && right subtree, then the length returned18
will be max of the left & right subtree , becuase ATQ, we have to19
return the longest path where each node in the path has the same20
value , therefore from the current node we can travel to either the21
left or right subtree , but the maxlength can be l.first+r.first+1 ,22
because we can travel from the leftmost node through the current23
node to the rightmost node , which will be a valid path , therefore24
we will compare this with the maxlength27
if (l.second == root->val && r.second == root->val) {28
maxlen = max(maxlen, l.first + r.first + 1);29
return {max(l.first, r.first) + 1, root->val};33
// now similary checking for all the other nodes:35
else if (l.second == root->val) {36
maxlen = max(maxlen, l.first + 1);37
return {l.first + 1, root->val};38
} else if (r.second == root->val) {39
maxlen = max(maxlen, r.first + 1);40
return {r.first + 1, root->val};42
return {1, root->val};45
int longestUnivaluePath(TreeNode *root) {47
util(root, root->val);48
return max(maxlen - 1, 0);