-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path687.cpp
More file actions
37 lines (37 loc) · 1.13 KB
/
687.cpp
File metadata and controls
37 lines (37 loc) · 1.13 KB
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
/**
* 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 {
public:
// {value, length}
int res = 0;
pair<int, int> dfs(TreeNode* node) {
if (node == nullptr) return {0, 0};
auto [leftValue, leftLength] = dfs(node->left);
auto [rightValue, rightLength] = dfs(node->right);
int currLength = 1;
int returnLength = 0;
if (leftValue == node->val) {
currLength += leftLength;
returnLength = max(returnLength, leftLength);
}
if (rightValue == node->val) {
currLength += rightLength;
returnLength = max(returnLength, rightLength);
}
res = max(res, currLength - 1);
return {node->val, returnLength + 1};
}
int longestUnivaluePath(TreeNode* root) {
dfs(root);
return res;
}
};