549. Binary Tree Longest Consecutive Sequence II
https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res = 0;
pair<int, int> dfs(TreeNode *root) {
if (root == nullptr) return {0, 0};
auto l = dfs(root->left), r = dfs(root->right);
int inc_res = 1, dec_res = 1;
if (root->left != nullptr) {
if (root->val == root->left->val + 1) inc_res = l.first + 1;
else if (root->val == root->left->val - 1) dec_res = l.second + 1;
}
if (root->right != nullptr) {
if (root->val == root->right->val + 1) inc_res = max(inc_res, r.first + 1);
else if (root->val == root->right->val - 1) dec_res = max(dec_res, r.second + 1);
}
res = max(res, inc_res + dec_res - 1);
return {inc_res, dec_res};
}
int longestConsecutive(TreeNode* root) {
dfs(root);
return res;
}
};Last updated