Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LC 637. 二叉树的层平均值 #27

Open
HealUP opened this issue May 18, 2023 · 0 comments
Open

LC 637. 二叉树的层平均值 #27

HealUP opened this issue May 18, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 18, 2023

637. 二叉树的层平均值

思路:

  • 层次遍历的时候,每一层求一个总和
  • 该层结束,就求这一层的平均值即可
class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        Queue<TreeNode> que = new LinkedList<>();
        //判断空
        if (root != null) {
            que.offer(root);
        }
        List<Double> list = new ArrayList<>();
        while (!que.isEmpty()) {
            int len = que.size();
            double sum = 0.0;
            for (int i = 0; i < len; i++) {//这里不能用while判断 会改变len的值
                TreeNode node = que.poll();//弹出并临时记录
                sum += node.val;//求和
                //将该层的平均值存放到一维数组中
                if (node.left != null) {
                    que.add(node.left);
                }
                if (node.right != null) {
                    que.add(node.right);
                }
            }
            list.add(sum / len);
        }
        return list;
    }
}

注意:这里不能用while

不能用 while(len > 0) {
    ...
    len--;
}
因为len改变了就无法计算sum/len了这点要注意
@HealUP HealUP added 算法 记录刷题记录,代码随想录 二叉树 labels May 18, 2023
@HealUP HealUP removed the 二叉树 label Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant