力扣 637. 二叉树的层平均值 C++ (DFS / BFS) 两种解法

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。

示例 1:

输入:
    3
   / \
  9  20
    /  \
   15   7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 ,1层是 14.5 ,2层是 11 。因此返回 [3, 14.5, 11]

提示:

  • 节点值的范围在32位有符号整数范围内。

C++(DFS)

class Solution {
public:
    vector<int> count;
    vector<double> sum;
    vector<double> average;
    vector<double> averageOfLevels(TreeNode* root) {
        dfs(root, 0);
        int sz = sum.size();
        for(int i = 0; i < sz; i++){
            average.push_back(sum[i] / count[i]);
        }
        return average;
    }
    void dfs(TreeNode* root, int level){
        if(root == nullptr){
            return;
        }
        if(level < sum.size()){
            sum[level] += root -> val;
            count[level] += 1;
        }else{
            sum.push_back(1.0 * root -> val);
            count.push_back(1);
        }
        dfs(root -> left, level + 1);
        dfs(root -> right, level + 1);
    }
};

C++(BFS)

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        queue<TreeNode*> que;
        if (root != NULL) que.push(root);
        vector<double> result;
        while (!que.empty()) {
            int size = que.size();
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                sum += node -> val;
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
            result.push_back( sum / size );
        }
        return result;
    }
};

你可能感兴趣的:(c++,二叉树,dfs,leetcode,bfs)