1. 程式人生 > >Leetcode 637. Average of Levels in Binary Tree

Leetcode 637. Average of Levels in Binary Tree

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