A few lines of JavaScript using DFS


  • 0
    var countUnivalSubtrees = function(root, res = { val: 0 }) {
        if (!root) return 0;
        res.val += isUnival(root, root.val);
        countUnivalSubtrees(root.left, res);
        countUnivalSubtrees(root.right, res);
        return res.val;
    };
    
    function isUnival(root, val) {
        return root ? root.val === val && isUnival(root.left, val) && isUnival(root.right, val) : true;
    }
    

Log in to reply
 

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