Simple C++ solution


  • 0
    M
    class Solution {
    private:    
            void _longestConsecutive(TreeNode* root,int count,int& max_count,TreeNode* prev)
        {
            if(root == NULL)
                return;
            
            if(prev != NULL && (prev->val + 1 == root->val))
            {
                count++;
            }
            else
            {
                count = 1;
            }
            
            max_count = count>max_count?count:max_count;
            
            prev = root;
            
            _longestConsecutive(root->left,count,max_count,prev);
            _longestConsecutive(root->right,count,max_count,prev);
            
            
        }
    public:
        
        int longestConsecutive(TreeNode* root) {
            
            if(root == NULL)
                return 0;
            
            int count = 1;
            int max_count = 0;
            
            TreeNode * prev = NULL;
            _longestConsecutive(root,count,max_count,prev);
            
            return max_count;
        }
    };
    

Log in to reply
 

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