LeetCode 637 二叉树的层平均值

LeetCode 637 二叉树的层平均值

题目链接

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

示例 1:

输入:

    3
   / \
  9  20
    /  \
   15   7

输出:

[3, 14.5, 11]

典型的 BFS,每层算一个答案即可,AC代码如下:

/**
 * 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:
    vector<double> averageOfLevels(TreeNode* root) {
    
    
        vector<double>ans;
        queue<TreeNode*>q;
        TreeNode* t=root;
        q.push(t);
        while(!q.empty()){
    
    
            int siz=q.size();
            double a=0,b=double(q.size());
            while(siz--){
    
    
                t=q.front();q.pop();
                if(t!=NULL){
    
    
                    a+=t->val;
                    if(t->left)q.push(t->left);
                    if(t->right) q.push(t->right);
                }
            }
            ans.push_back(a/b);
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/108547666