549. Binary Tree Longest Consecutive Sequence II

https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/

二叉树上结点值满足递增或递减的最长路径的长度。结果分为当前结点和左,右或左和右结果拼接在一起,分治,递归时返回包含当前结点的path最长递增和递减路径长度,并global统计左右和当前连一起时的结果。递归内部分类讨论左,右子树,递增和递减对应的结果。

/**
 * 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