Very efficient and simple to understand C++ solution


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int longestConsecutive(TreeNode* root) {
            int max_len(0);
            DFS(root, nullptr, 0, max_len);
            return max_len;
        }
    private:
        void DFS(TreeNode *root, TreeNode *parent, int len, int &max_len) {
            if (!root) return;
            
            if (parent && root->val == parent->val + 1) len += 1;
            else len = 1; // New path begins
            
            max_len = std::max(max_len, len);
            
            DFS(root->left, root, len, max_len);
            DFS(root->right, root, len, max_len);
        }
    };
    

Log in to reply
 

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