[LeetCode][637]Average of Levels in Binary Tree题解

版权声明:请注明转载地址 https://blog.csdn.net/OCEANtroye https://blog.csdn.net/OCEANtroye/article/details/83714040

[LeetCode][637]Average of Levels in Binary Tree题解


标签:BFS queue
题意:求树的每层的平均数
使用bfs即可
code:

/*
 * [637] Average of Levels in Binary Tree
 *
 * https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
 *
 * algorithms
 * Easy (56.87%)
 * Total Accepted:    61.1K
 * Total Submissions: 107.4K
 * Testcase Example:  '[3,9,20,15,7]'
 *
 * 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.
 *
 *
 */
/**
 * 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)
    {
        //bfs
        if (root == nullptr)
        {
            return vector<double>{};
        }

        vector<double> res;
        queue<TreeNode *> q;
        q.push(root);
        while (!q.empty())
        {
            long long temp=0;
            int n=q.size();
            //该层次的所有元素
            for(int i=0;i<n;i++)
            {
                TreeNode *t=q.front();
                q.pop();
                if(t->left)
                {
                    q.push(t->left);
                }
                if(t->right)
                {
                    q.push(t->right);
                }
                temp+=t->val;
            }
            res.push_back((double)temp/n);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/OCEANtroye/article/details/83714040