[LeetCode] Longest Univalue Path

687. Longest Univalue Path

Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

The length of the path between two nodes is represented by the number of edges between them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int res = 0;
int path(TreeNode* root) {
int left(0), right(0);
if(root->left) {
if(root->left->val == root->val) {
left = path(root->left);
} else {
path(root->left);
}
}

if(root->right) {
if(root->right->val == root->val) {
right = path(root->right);
} else {
path(root->right);
}
}
res = max(res, left + right);
return max(left, right) + 1;
}
public:
int longestUnivaluePath(TreeNode* root) {
if(!root) return 0;
path(root);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/23/PS/LeetCode/longest-univalue-path/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.