637. Average of Levels in Binary Tree - LeetCode

?题目描述

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

示例 1:

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

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

 ?Method 1: DFS , preorderTraversal_recursive

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 // DFS做法,先序遍历
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        if (root == nullptr) { return {};} // C++11新标准推荐nullptr
        //由于节点值的范围在32位有符号整数范围,所以求和用longlong保险起见↓
        vector<pair<long long,int>> sum_count; //把两个数组合成一个pair vector↓
        vector<double> ans;

        preorder(root, 0, sum_count);
        // dfs递归处理完之后,才能知道每一层的sum和count,才能进行下面最终的操作
        // 而第二种方法 bfs不需要递归,一层一层做
        for (const auto &p : sum_count) { //  "range-based for-loops".
            // C++11新标准推荐static_cast<double>()类型转换
            ans.push_back(static_cast<double>(p.first) / p.second);
        }
        return ans;
    }

private:
    void preorder(TreeNode* root,int depth,vector<pair<long long,int>> &sum_count){
        if (root == nullptr)  return;
        if (depth >= sum_count.size()) sum_count.push_back({0,0}); //因为sum_count没有初始化和构造过,所以动态的去更新它
        sum_count[depth].first += root->val; // 每一层的和
        ++sum_count[depth].second; //每一层节点个数
        preorder(root->left, depth + 1, sum_count);
        preorder(root->right, depth + 1, sum_count);
    }
};

?Method 2: BFS 的话就不需要递归,一个while循环就可以, 不断创建你下一层要访问的节点


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
//BFS
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        if(root == nullptr) return {};
        vector<double> ans;

        vector<TreeNode*> curr, next; // 当前节点,下一层节点
        curr.push_back(root);

        // process every leverl one by one
        // BFS 的话就不需要递归,一个while循环就可以了,不断创建你下一层要访问的节点
        while (!curr.empty()) {
            long long sum = 0;
            for (const auto &node:curr) {
                sum += node->val;
                if (node->left) next.push_back(node->left); //如果当前节点有左节点,就将它加入next
                if (node->right) next.push_back(node->right);
            }
            ans.push_back(static_cast<double>(sum) / curr.size());
            //swap 不涉及复制,相当于把内部的指针对调一下,curr指向next之前指向的区域。
            curr.swap(next);
            next.clear();
        }
        return ans;
    }
};

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值