Short C++ solution with C++11 features


  • 0
    Y
    int max_len;
    
    tuple<int, int> Visit(TreeNode* node) {
        int inc_dist = 0;
        int dec_dist = 0;
        for (auto child : {node->left, node->right}) {
            if (child == nullptr) {
                continue;
            }
            int child_inc_dist;
            int child_dec_dist;
            tie(child_inc_dist, child_dec_dist) = Visit(child);
            if (child->val + 1 == node->val) {
                inc_dist = max(inc_dist, child_inc_dist + 1);
            }
            if (child->val - 1 == node->val) {
                dec_dist = max(dec_dist, child_dec_dist + 1);
            }
        }
        max_len = max(max_len, inc_dist + dec_dist + 1);
        return {inc_dist, dec_dist};
    }
    
    class Solution {
    public:
        int longestConsecutive(TreeNode* root) {
            max_len = 0;
            if (root != nullptr) {
                Visit(root);
            }
            return max_len;
        }
    };
    

Log in to reply
 

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