一、題目大意
給定一個非空二叉樹的根節點 root , 以陣列的形式回傳每一層節點的平均值,與實際答案相差 10-5 以內的答案可以被接受,
示例 1:

輸入:root = [3,9,20,null,null,15,7]
輸出:[3.00000,14.50000,11.00000]
解釋:第 0 層的平均值為 3,第 1 層的平均值為 14.5,第 2 層的平均值為 11 ,
因此回傳 [3, 14.5, 11] ,
示例 2:

輸入:root = [3,9,20,15,7]
輸出:[3.00000,14.50000,11.00000]
提示:
-
樹中節點數量在 [1, 104] 范圍內
-
-231 <= Node.val <= 231 - 1
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/average-of-levels-in-binary-tree
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
二、解題思路
求一個二叉樹每層的平均值,利用廣度優先搜索,我們可以很方便地求取每層的平均值,直接使用queue,直接將每層的值累計加起來除以該層的節點個數,存入結果ans中即可,
三、解題方法
3.1 Java實作
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> ans = new ArrayList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int count = q.size();
double sum = 0;
for (int i = 0; i < count; i++) {
TreeNode node = q.peek();
q.poll();
sum += node.val;
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
}
ans.add(sum / count);
}
return ans;
}
}
四、總結小記
- 2022/9/15 notion是pld的典范,什么是PLG,product-led groupth,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508798.html
標籤:其他
上一篇:資料結構(一):什么是資料結構?
