Question - C++ - Why did we add the max between count and max(right, left)


  • 0
    M

    I wrote my code without the outer max call and it failed a test case. So I looked that my solution is missing an outer max call between the count and max (left, right). Could anyone please explain why we did so?

    class Solution {
    private:
        int longestConsecutive(TreeNode* root, int count, int val) {
            if (!root)  return count;
            count = (root->val - val == 1)? count + 1 : 1;
            int left  = longestConsecutive(root->left, count, root->val);
            int right = longestConsecutive(root->right, count, root->val);
            return max(max(left, right), count);        // why this outer max? 
        }
    public:
        int longestConsecutive(TreeNode* root) {
            return (!root)? 0 : max(longestConsecutive(root->right, 1, root->val), longestConsecutive(root->left, 1, root->val));
        }
    };
    

Log in to reply
 

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