我正在嘗試查找二叉樹中每個級別的平均值。我在做BFS。我正在嘗試使用空節點來完成它。每當我找到一個虛擬節點時,這意味着我處於該級別的最後一個節點。我面臨的問題是,我無法使用此功能在樹中添加最後一級的平均值。有人能幫我嗎?二叉樹中每個級別的平均值
考慮範例[3,9,20,15,7] 我得到的輸出爲[3.00000,14.50000]。沒有得到最後一級是15和7 的平均這裏是我的代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list = new ArrayList<Double>();
double sum = 0.0;
Queue<TreeNode> q = new LinkedList<TreeNode>();
TreeNode temp = new TreeNode(0);
q.offer(root);
q.offer(temp);
int count = 0;
while(!q.isEmpty()){
root = q.poll();
sum += root.val;
if(root != temp)
{
count++;
if(root.left != null){
q.offer(root.left);
}
if(root.right != null){
q.offer(root.right);
}
}
else
{
if(!q.isEmpty()){
list.add(sum/count);
sum = 0;
count = 0;
q.add(temp);
}
}
}
return list;
}
}