Short and clear JavaScript solution using DFS


  • 0
    var longestConsecutive = function(root, res = { val: 0 }) {
        if (!root) return 0;
        const left1 = consecutive(root, -1);
        const right1 = consecutive(root);
        const left2 = consecutive(root);
        const right2 = consecutive(root, -1);
        res.val = Math.max(res.val, Math.max(left1 + right1 - !!(left1 && right1), left2 + right2 - !!(left2 && right2)));
        longestConsecutive(root.left, res);
        longestConsecutive(root.right, res);
        return res.val;
    };
    
    function consecutive(root, dir = 1, prev = null) {
        if (!root || prev !== null && root.val !== prev + dir) return 0;
        return 1 + Math.max(consecutive(root.left, dir, root.val), consecutive(root.right, dir, root.val));
    }
    

Log in to reply
 

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