Leetcode637.二叉樹的層平均值 Average of Levels in Binary Tree(Java)
阿新 • • 發佈:2020-12-23
Leetcode637.二叉樹的層平均值 Average of Levels in Binary Tree(Java)
##Tree##
本題求二叉樹每層的結點平均值
可以採用DFS、BFS
這裡採用BFS層次遍歷
- 佇列
q
中元素為某一層的結點,count = q.size()
代表隊列中元素的個數 - 迴圈
count
次,遍歷佇列q
中所有結點,求出該層所有結點的和sum
,並且對每個結點都需要將其左右兒子加入佇列中 - 將每層的平均值
sum/count
加入到結果集合中
時間複雜度: O(n)
class Solution {
public List< Double> averageOfLevels(TreeNode root) {
List<Double> ans = new LinkedList<Double>();
Queue<TreeNode> q = new LinkedList<>();
if (root == null) return ans;
q.add(root);
while(!q.isEmpty()) {
double sum = 0;
int count = q.size();
TreeNode curr;
for (int i = 0; i < count; i ++) {
curr = q.poll();
sum += curr.val;
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
}
ans. add(sum / count);
}
return ans;
}
}