forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0687.cpp
More file actions
26 lines (24 loc) · 682 Bytes
/
0687.cpp
File metadata and controls
26 lines (24 loc) · 682 Bytes
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
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
int longestUnivaluePath(TreeNode* root)
{
res = 0;
longestUnivalue(root);
return res;
}
private:
int res;
int longestUnivalue(TreeNode* root)
{
if (root == nullptr) return 0;
int l = longestUnivalue(root->left);
int r = longestUnivalue(root->right);
int pl = 0, pr = 0;
if (root->left and root->left->val == root->val) pl = l + 1;
if (root->right and root->right->val == root->val) pr = r + 1;
res = max(res, pl + pr);
return max(pl, pr);
}
};