原文链接 [链接] Description: 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 ..

[每日 LeetCode] 637. Average of Levels in Binary Tree

原文链接 [每日LeetCode] 637. Average of Levels in Binary Tree

Description:

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:

  1. The range of node's value is in the range of 32-bit signed integer.

思路:本题要求二叉树每层结点的平均值,返回此平均值数组。可借助[每日LeetCode] 102. Binary Tree Level Order Traversal 层序遍历思想,对每层结点入队后进行求平均值操作,最后返回每层结点平均值数组。


C++ 代码

/**
 * 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 == NULL)
            return v;
        queue<TreeNode*> q;
        vector<int> a;
        q.push(root);
        q.push(NULL);
        while(!q.empty())
        {
            TreeNode* temp  = q.front();
            q.pop();
            if(temp==NULL)
            {
                double sum=0;
                for(int i=0;i<a.size();i++)
                     sum+=a[i];
                sum = sum/a.size();
                v.push_back(sum);
                a.clear();
                if(!q.empty())
                    q.push(NULL);
            }
            else
            {
                a.push_back(temp->val);
                if(temp->left)
                     q.push(temp->left);
                if(temp->right)
                     q.push(temp->right);
            }
        }        
        return v;
    }
};

运行时间:20ms

运行内存:22M

  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    165 引用 • 61 回帖
  • LLVM
    19 引用 • 2 回帖
  • Tree
    34 引用 • 5 回帖
  • Easy
    101 引用 • 10 回帖
回帖
请输入回帖内容...