Leetcode 637. Average of Levels in Binary Tree

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82791715

文章作者: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/

猜你喜欢

转载自blog.csdn.net/Quincuntial/article/details/82791715
今日推荐