straightforward c++ method


  • 0
    M
    class Solution {
    public:
        int longestConsecutive(TreeNode* root) {
            if(not root) return 0;
            return max(cntfrom(root), max(longestConsecutive(root->left),longestConsecutive(root->right)));
        }
        int cntfrom(TreeNode* root){
            if(not root) return 0;
            int cnt = 1;
            int left = cnt + ( (root->left and root->left->val == root->val +1)? cntfrom(root->left):0 ); 
            int right = cnt + ( (root->right and root->right->val == root->val +1 )? cntfrom(root->right):0 ); 
            return max(left, right);
        }
    };
    

Log in to reply
 

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