leetCode_637_AverageOfLevelsInBinaryTree
来源:互联网 发布:php ipv6适配 编辑:程序博客网 时间:2024/06/09 23:40
题目描述
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */import java.util.Queue;class Solution { public List<Double> averageOfLevels(TreeNode root) { if (root == null) return null; List<Double> list = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); list.add((double)root.val); queue.add(root); TreeNode last = root; TreeNode nextLast = root; double averageSum = 0; int count = 0; while (queue.size() != 0) { TreeNode temp = queue.poll(); if (temp.left != null) { nextLast = temp.left; queue.add(temp.left); averageSum += temp.left.val; count ++; } if (temp.right != null) { nextLast = temp.right; queue.add(temp.right); averageSum += temp.right.val; count ++; } if (temp == last) { if (nextLast != last) { list.add(averageSum / count); averageSum = 0; count = 0; last = nextLast; } } } return list; }}
阅读全文
0 0
- leetCode_637_AverageOfLevelsInBinaryTree
- 9月30日云栖精选夜读:阿里巴巴摘得LSVC桂冠 打造领先AI视频技术
- tomcat启动成功,访问tomcat主页显示404
- Silver Cow Party POJ
- python3爬虫初探(一)之urllib.request
- Socket详解
- leetCode_637_AverageOfLevelsInBinaryTree
- 搜索引擎优化是项目的开始,而不是结束的原因
- OLTP/OLAP
- 【分布式6】Zookeeper使用--Java API
- es6语法-解构赋值
- 初识Spring Boot框架(二)之DIY一个Spring Boot的自动配置
- ios开发之本地通知
- HttpUtils
- How to monkeypatch a staticmethod/classmethod/instancemethod?