-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path298.cpp
27 lines (27 loc) · 816 Bytes
/
298.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
/**
* 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 res = 0;
void dfs(TreeNode* node, TreeNode* parent, int length) {
if (node == nullptr) return;
if (parent != nullptr && node->val - parent->val == 1) length++;
else length = 1;
res = max(res, length);
dfs(node->left, node, length);
dfs(node->right, node, length);
}
int longestConsecutive(TreeNode* root) {
dfs(root, nullptr, 0);
return res;
}
};