leetcode 637 C++ 16ms 二叉树的层平均值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

#include<queue>


class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> res;
        queue<TreeNode*> q;
        q.push(root);
        long int sum = 0;
        int node_num;
        while(!q.empty()){
            sum = 0;
            node_num = (int)q.size();
            for(int i=0;i<node_num;i++){
                auto node = q.front();
                q.pop();
                sum += node->val;
                if(node->left != nullptr){
                    q.push(node->left);
                }
                if(node->right != nullptr){
                    q.push(node->right);
                }
            }
            res.push_back((double)sum/node_num);
        }
        return res;
    }
};


posted @ 2018-07-30 00:00  一条图图犬  阅读(347)  评论(0编辑  收藏  举报