Javascript solution sharing


  • 0
    A

    The idea is sum of each level divided by count of each level

    var averageOfLevels = function(root) {
        var sumArr = [];
        var countArr = [];
        var sum = function(node, level) {
            if (!node) return
            if (!sumArr[level]) sumArr[level] = 0;
            sumArr[level] += node.val;
            if (!countArr[level]) countArr[level] = 0;
            countArr[level]++;
            sum(node.left, level + 1);
            sum(node.right, level + 1);
        }
        sum(root, 0);
        var meanArr = sumArr.map((sum, level) => sum / countArr[level]);
        return meanArr;
    };
    

  • 0
    W

    @Asing1001 said in Javascript solution sharing:

    countArr

    seems one typo which is levelCountArr which should be countArr.


  • 0
    A

    @whxjenny Thanks, I fix the typo


Log in to reply
 

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