My C++ 4 lines recursive solution - 40ms


  • 2
    E
    class Solution {
    public:
        int longestConsecutive(TreeNode* root) {
            return helper(root, NULL, 0);
        }
    private:
        int helper(TreeNode* root, TreeNode* parent, int length) {
            if(root == NULL) return length;
            length = (parent && root -> val == parent -> val + 1) ? length + 1 : 1;
            return max(length, max(helper(root -> left, root, length), helper(root -> right, root, length)));
        }
    };

Log in to reply
 

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