[LeetCode] Average of Levels in Binary Tree 二叉树的层平均值

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

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]. 

Note:

  1. The range of node's value is in the range of 32-bit signed integer. 

这道题让我们求一个二叉树每层的平均值,那么一看就是要进行层序遍历了,直接上queue啊,如果熟悉层序遍历的方法,那么这题就没有什么难度了,直接将每层的值累计加起来,除以该层的结点个数,存入结果res中即可,参见代码如下:

解法一:

class Solution {

public:
    vector<double> averageOfLevels(TreeNode* root) {
        if (!root) return {};
        vector<double> res;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            int n = q.size();
            double sum = 0;
            for (int i = 0; i < n; ++i) {
                TreeNode *t = q.front(); q.pop();
                sum += t->val;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.push_back(sum / n);
        }
        return res;
    }
};

下面这种方法虽然是利用的递归形式的先序遍历,但是其根据判断当前层数level跟结果res中已经初始化的层数之间的关系对比,能把当前结点值累计到正确的位置,而且该层的结点数也自增1,这样我们分别求了两个数组,一个数组保存了每行的所有结点值,另一个保存了每行结点的个数,这样对应位相除就是我们要求的结果了,参见代码如下:

解法二:

class Solution {

public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> res, cnt;
        helper(root, 0, cnt, res);
        for (int i = 0; i < res.size(); ++i) {
            res[i] /= cnt[i];
        }
        return res;
    }
    void helper(TreeNode* node, int level, vector<double>& cnt, vector<double>& res) {
        if (!node) return;
        if (res.size() <= level) {
            res.push_back(0);
            cnt.push_back(0);
        }
        res[level] += node->val;
        ++cnt[level];
        helper(node->left, level + 1, cnt, res);
        helper(node->right, level + 1, cnt, res);
    }
};

参考资料:

https://discuss.leetcode.com/topic/95567/java-solution-using-dfs-with-full-comments

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Average of Levels in Binary Tree 二叉树的层平均值

,如需转载请自行联系原博主。

时间: 2024-09-23 12:31:20

[LeetCode] Average of Levels in Binary Tree 二叉树的层平均值的相关文章

leetcode 104 Maximum Depth of Binary Tree二叉树求深度

Maximum Depth of Binary Tree Total Accepted: 63668 Total Submissions: 141121 My Submissions Question Solution Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the

[LeetCode] Maximum Width of Binary Tree 二叉树的最大宽度

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level

[LeetCode] Second Minimum Node In a Binary Tree 二叉树中第二小的结点

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.

[LeetCode] Invert Binary Tree - 二叉树翻转系列问题

目录:1.Invert Binary Tree - 二叉树翻转 [递归] 题目概述: Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by this original tweet by Max Howell: Google: 90% of our engineers use the software you wrote (H

[LeetCode]111.Minimum Depth of Binary Tree

[题目] Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. [分析] 类似于:LeetCode之Maximum Depth of Binary Tree [代码] /********************************

LeetCode 104 Maximum Depth of Binary Tree(二叉树的最大深度)

翻译 给定一个二叉树,找出它的最大深度. 最大深度是指的从根节点一直到最远的叶节点中所有的节点数目. 原文 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 代码 /** * Definition for a binary tre

[LeetCode]104.Maximum Depth of Binary Tree

[题目] Maximum Depth of Binary Tree  Total Accepted: 5260 Total Submissions: 11532My Submissions Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf n

[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)

目录:1.Binary Tree Level Order Traversal - 二叉树层次遍历 BFS 2.Binary Tree Level Order Traversal II - 二叉树层次遍历从低往高输出 BFS 3.Maximum Depth of Binary Tree - 求二叉树的深度 DFS4.Balanced Binary Tree - 判断平衡二叉树 DFS5.Path Sum - 二叉树路径求和判断DFS 题目概述:Given a binary tree, return

[LeetCode] Maximum Binary Tree 最大二叉树

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number