C++ solution


  • 0
    H
        int longestConsecutive(TreeNode* root) {
            if (!root)
                return 0;
            int res = helper(root, 1) + helper(root, -1) + 1;
            return max(max(res, longestConsecutive(root->left)), longestConsecutive(root->right));
        }
        int helper(TreeNode* root, int diff)
        {
            if (!root)
                return 0;
    
            TreeNode* left = root->left;
            TreeNode* right = root->right;
            int len_l = 0;
            int len_r = 0;
            
            if (left)
                if (root->val - left->val == diff)
                    len_l = 1 + helper(left, diff);
            if (right)
                if (root->val - right->val == diff)
                    len_r = 1 + helper(right, diff);
            return max(len_l, len_r);
        }
    

Log in to reply
 

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