637. Average of Levels in Binary Tree

2018/05/01 leetcode 共 860 字,约 3 分钟

Title

the problem link

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input:

    3
   / \
  9  20
    /  \
   15   7

Output: [3, 14.5, 11]

Explanation:

The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note: The range of node’s value is in the range of 32-bit signed integer.

求树每层的平均值,bfs

Solution

//cpp:
/**
 * 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) {
        queue<TreeNode*> q;
        vector<double> v;
        int last=1;
        if(!root)
            return v;
        q.push(root);
        while(!q.empty()){
            double ans=0;
            for(int i=0;i<last;i++){
                TreeNode* t1=q.front();
                ans+=t1->val;
                q.pop();
                if(t1->left){
                    q.push(t1->left);
                }
                if(t1->right){
                    q.push(t1->right);
                }
            }
            v.push_back(ans/last);
            last=q.size();
        }
        return v;
        
    }
}

Search

    Table of Contents