LeetCode 637. Average of (average value of each node of the binary tree) Levels in Binary Tree

The meaning of problems: averaging each node of the binary tree.

Analysis: BFS traverse the hierarchy, each step process an entire loop disposable layer.

/**
 * 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;
        if(root == NULL) return ans;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int len = q.size();
            double sum = 0;
            for(int i = 0; i < len; ++i){
                TreeNode *tmp = q.front();
                q.pop();
                sum += double(tmp -> val);
                if(tmp -> left != NULL) q.push(tmp -> left);
                if(tmp -> right != NULL) q.push(tmp -> right);
            }
            ans.push_back(sum / len);
        }
        return ans;
        
    }
};

  

 

Guess you like

Origin www.cnblogs.com/tyty-Somnuspoppy/p/12521322.html