Lintcode 1115 · Average of Levels in Binary Tree (BFS/DFS 经典题)

文章介绍了如何使用深度优先搜索(DFS)和广度优先搜索(BFS)算法在给定的非空二叉树中计算每个层级的节点平均值,给出了C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1115 · Average of Levels in Binary Tree
Algorithms
Description
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
The range of node’s value is in the range of 32-bit signed integer.
Example
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].
Tags
Company
Facebook

解法1:DFS

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the binary tree of the  root
     * @return: return a list of double
     */
    vector<double> averageOfLevels(TreeNode * root) {
        if (!root) return {};
        vector<double> avgs;
        vector<int> counts;

        helper(root, 0, avgs, counts);
        for (int i = 0; i < avgs.size(); i++) {
            avgs[i] /= 1.0 * counts[i];
        }
        return avgs;
    }
private:
    void helper(TreeNode*root, int depth, vector<double> &avgs, vector<int> &counts) {
        if (!root) return;
        if (depth == avgs.size()) {
            avgs.push_back(1.0 * root->val);
            counts.push_back(1);
        } else { //depth < avgs.size(). It is impossible that depth > avgs.size()
            //avgs.back() += 1.0 * root->val;   //不对
            //counts.back()++; //不对
            avgs[depth] += 1.0 * root->val;
            counts[depth]++;

        }
        if (root->left) helper(root->left, depth + 1, avgs, counts);
        if (root->right) helper(root->right, depth + 1, avgs, counts);
        return;
    }
};

解法2:BFS

class Solution {
public:
    /**
     * @param root: the binary tree of the  root
     * @return: return a list of double
     */
    vector<double> averageOfLevels(TreeNode * root) {
        if (!root) return {};
        vector<double> res;
        queue<TreeNode *> q;
        q.push(root);

        while (!q.empty()) {
            int qSize = q.size();
            double sum = 0.0;
            for (int i = 0; i < qSize; i++) {
                TreeNode *front = q.front();
                q.pop();
                sum += front->val;
                if (front->left) q.push(front->left);
                if (front->right) q.push(front->right);
            }
            res.push_back(sum / (1.0 * qSize));
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值