forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
38 lines (36 loc) · 1.11 KB
/
Solution.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
/**
* 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:
int ans;
int longestConsecutive(TreeNode* root) {
ans = 0;
dfs(root);
return ans;
}
vector<int> dfs(TreeNode* root) {
if (!root) return {0, 0};
int incr = 1, decr = 1;
auto left = dfs(root->left);
auto right = dfs(root->right);
if (root->left) {
if (root->left->val + 1 == root->val) incr = left[0] + 1;
if (root->left->val - 1 == root->val) decr = left[1] + 1;
}
if (root->right) {
if (root->right->val + 1 == root->val) incr = max(incr, right[0] + 1);
if (root->right->val - 1 == root->val) decr = max(decr, right[1] + 1);
}
ans = max(ans, incr + decr - 1);
return {incr, decr};
}
};