298. Binary Tree Longest Consecutive Sequence
Difficulty: Medium
Given the root of a binary tree, return the length of the longest consecutive sequence path.
A consecutive sequence path is a path where the values increase by one along the path.
Note that the path can start at any node in the tree, and you cannot go from a node to its parent in the path.
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
|
/**
* 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 longestConsecutive(TreeNode* root) {
DFS(root);
return maxlen_;
}
private:
int DFS(TreeNode* node) {
int left = 0, right = 0;
if (node->left != nullptr) {
if (node->left->val == node->val + 1) {
left = DFS(node->left);
}
else {
DFS(node->left);
}
}
if (node->right != nullptr) {
if (node->right->val == node->val + 1) {
right = DFS(node->right);
}
else {
DFS(node->right);
}
}
int res = 1 + std::max(left, right);
maxlen_ = std::max(maxlen_, res);
return res;
}
int maxlen_ = 0;
};
|
