easy to understand C++ solution


  • 0
    I
    class Solution {
    public:
        int decreasingParentToChild(TreeNode *root, int val)
        {
            if(!root || root->val != val-1) return 0;
            return 1 + max(decreasingParentToChild(root->left,root->val),decreasingParentToChild(root->right,root->val));
        }
        int increasingParentToChild(TreeNode *root, int val)
        {
            if(!root || root->val != val+1) return 0;
            return 1 + max(increasingParentToChild(root->left,root->val),increasingParentToChild(root->right,root->val));
        }
        void helper(TreeNode *root, int &res)
        {
            if(!root)
              return;
            int left_dec = decreasingParentToChild(root->left,root->val);
            int left_inc = increasingParentToChild(root->left,root->val);
            int right_dec = decreasingParentToChild(root->right,root->val);
            int right_inc = increasingParentToChild(root->right,root->val);
            res = max(res,left_dec+1+right_inc);
            res = max(res,left_inc+1+right_dec);
            helper(root->left,res);
            helper(root->right,res);
    
        }
        int longestConsecutive(TreeNode* root) {
            if(!root)
               return 0;
            int res = 1;
            helper(root,res);
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.