-
Notifications
You must be signed in to change notification settings - Fork 14
/
687-gusrb3164.cpp
49 lines (48 loc) · 1.06 KB
/
687-gusrb3164.cpp
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
41
42
43
44
45
46
47
48
49
/**
* 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 result = 0;
public:
int longestUnivaluePath(TreeNode *root)
{
dfs(root);
return result;
}
int dfs(TreeNode *cur)
{
if (cur == nullptr)
{
return 0;
}
int left = dfs(cur->left);
int right = dfs(cur->right);
if (cur->left != nullptr && cur->val == cur->left->val)
{
left++;
}
else
{
left = 0;
}
if (cur->right != nullptr && cur->val == cur->right->val)
{
right++;
}
else
{
right = 0;
}
result = max(result, left + right);
return max(left, right);
}
};