C++/c clean recursive solution 44 ms


  • 0
    R
    class Solution {
    public:
    
        void get_max_seq(TreeNode *root, TreeNode *par, int cnt, int *longest) {
            if(NULL == root) {
                return;
            }
            
            if((NULL == par) || (par->val == (root->val - 1))) {
                cnt += 1;
                (*longest) = max(cnt, *longest);
            } else {
                cnt = 1;
            }
            
            get_max_seq(root->left, root, cnt, longest);
            get_max_seq(root->right, root, cnt, longest);
            
        }
    
        int longestConsecutive(TreeNode* root) {
            int cnt = 0;
            int max = 0;
            TreeNode *par = NULL;
    
            get_max_seq(root, par, cnt, &max);
            return max;
        }
    };

Log in to reply
 

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