[Daily question] 34: Layer average of binary tree

Title description

Given a non-empty binary tree, return an array consisting of the average of nodes at each level.

Example 1:

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

note:

The range of node values ​​is in the range of 32-bit signed integers.

Answer code:

/**
 * 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> v;

        if(!root){
            return v;
        }

		// 建立一个临时存储的数组
        vector<int> temp;
        queue<TreeNode*> qu;
        TreeNode* cur;
        qu.push(root);
        
        while(!qu.empty()){
            int len = qu.size();
            for(int i = 0; i < len; i++){
                cur = qu.front();
                temp.push_back(cur->val);
                qu.pop();

                if(cur->left){
                    qu.push(cur->left);
                }
                if(cur->right){
                    qu.push(cur->right);
                }
            }
            double sum = 0;
            for(auto i : temp){
                sum += i;
            }
            sum /= len;

            v.push_back(sum);
            temp.clear();
        }

        return v;
    }
};

If you have different opinions, please leave a message to discuss ~~

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105410793