549. Binary Tree Longest Consecutive Sequence II

549. Binary Tree Longest Consecutive Sequence II

Description

Given the root of a binary tree, return the length of the longest consecutive path in the tree.

A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.

  • For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid.

On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.

Example 1:

1
2
3
Input: root = [1,2,3]
Output: 2
Explanation: The longest consecutive path is [1, 2] or [2, 1].

Example 2:

1
2
3
Input: root = [2,1,3]
Output: 3
Explanation: The longest consecutive path is [1, 2, 3] or [3, 2, 1].

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 10^4].
  • -3 * 10^4 <= Node.val <= 3 * 10^4

Hints/Notes

  • N/A

Solution

Language: C++

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
50
51
52
/**
* 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;

int longestConsecutive(TreeNode* root) {
traverse(root);
return res;
}

// the return pair: the length of longest increasing/decreasing sequence at root
pair<int, int> traverse(TreeNode* root) {
if (!root) {
return {0, 0};
}

int inc = 1, dec = 1, l = 1, r = 1;
if (root->left) {
auto left = traverse(root->left);
if (root->val == root->left->val + 1) {
inc += left.first;
l = max(l, 1 + left.first);
} else if (root->val == root->left->val - 1) {
dec += left.second;
r = max(r, 1 + left.second);
}
}
if (root->right) {
auto right = traverse(root->right);
if (root->val == root->right->val + 1) {
dec += right.first;
l = max(l, 1 + right.first);
} else if (root->val == root->right->val - 1) {
inc += right.second;
r = max(r, 1 + right.second);
}
}
res = max(res, max(inc, dec));
return {l, r};
}
};