美文网首页Leetcode
Leetcode 637. Average of Levels

Leetcode 637. Average of Levels

作者: SnailTyan | 来源:发表于2018-09-20 18:29 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Average of Levels in Binary Tree

    2. Solution

    • Version 1
    /**
     * 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> result;
            if(!root) {
    
            }
            queue<TreeNode*> q;
            q.push(root);
            q.push(nullptr);
            double sum = 0;
            int count = 0;
            while(!q.empty()) {
                TreeNode* current = q.front();
                q.pop();
                if(current) {
                    count++;
                    sum += current->val;
                    if(current->left) {
                        q.push(current->left);
                    }
                    if(current->right) {
                        q.push(current->right);
                    }
                }
                else if(count){
                    double mean = sum / count;
                    sum = 0;
                    count = 0;
                    result.push_back(mean);
                    q.push(nullptr);
                }
            }
            return result;
        }
    };
    
    • Version 2
    /**
     * 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> result;
            if(!root) {
                return result;
            }
            queue<TreeNode*> q;
            q.push(root);
            double sum = 0;
            while(!q.empty()) {
                sum = 0;
                int size = q.size();
                for(int i = 0; i < size; i++) {
                    TreeNode* current = q.front();
                    q.pop();
                    sum += current->val;
                    if(current->left) {
                        q.push(current->left);
                    }
                    if(current->right) {
                        q.push(current->right);
                    }
                }
                result.push_back(sum / size);
            }
            return result;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/average-of-levels-in-binary-tree/description/

    相关文章

      网友评论

        本文标题:Leetcode 637. Average of Levels

        本文链接:https://www.haomeiwen.com/subject/musnnftx.html