[LeetCode javaScript] 637. 二叉树的层平均值

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

示例 1:

输入:
3
/
9 20
/
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
注意:

节点值的范围在32位有符号整数范围内。

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var averageOfLevels = function(root) {
    var getPj=function(arr){
        var count=0;
        for(var i in arr){
            count+=arr[i];
        }
        return count/arr.length;
    }
    if(root==null){
        return [];
    }
    var result=[];
    var queue=[];
    queue.push(root);
    while(queue.length!=0){
        var nodes=[];
        var nodesValue=[];
        for (var i in queue){
            if(queue[i].left!=null){
                nodes.push(queue[i].left);
            }
            if(queue[i].right!=null){
                nodes.push(queue[i].right);
            }
            nodesValue.push(queue[i].val);
        }
        queue=nodes;
        result.push(getPj(nodesValue));
    }
    return result;
};

猜你喜欢

转载自blog.csdn.net/qq_40547126/article/details/82907329