Leetcode 298 Binary Tree Longest Consecutive Sequence

weixin_34253539發表於2018-09-05
class Solution {
public:
    
    int search_util(TreeNode *root){
        if(!root){
            return 0;
        }
        
        int left = search_util(root->left);
        int right = search_util(root->right);
        
        int cur_left = 1, cur_right = 1;
        if(root->left && root->val == root->left->val - 1){
            cur_left = left + 1;
        }
        
        if(root->right && root->val == root->right->val - 1){
            cur_right = right + 1;
        }
        
        int cur_max = max(cur_left, cur_right);
        max_count = max(max_count, cur_max);
        return cur_max;
    }
    
    int longestConsecutive(TreeNode* root) {
        if(!root){
            return 0;
        }
        
        search_util(root);
        return max_count;
    }
private:
    int max_count;
};

相關文章