Share my 3 line C++ solution


  • 2
    J
    class Solution {
    public:
        int findLongestConsecutive(TreeNode *root, int num, int length, int maximum)
        {
            if (root == NULL)
                return maximum;
            if (root->val == num + 1)
                return max(findLongestConsecutive(root->left, root->val, length + 1, max(maximum, length + 1)),
                        findLongestConsecutive(root->right, root->val, length + 1, max(maximum, length + 1)));
            else
                return max(findLongestConsecutive(root->left, root->val, 1, maximum),
                           findLongestConsecutive(root->right, root->val, 1, maximum));
        }
        int longestConsecutive(TreeNode* root) {
            return findLongestConsecutive(root, root->val - 1, 0, 0);
        }
    };
    

    Indented and line separated to make it easier to read.


  • 0
    T
    This post is deleted!

Log in to reply
 

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