Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
树的BFS遍历 没啥好说的
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
ArrayList<Double> result =new ArrayList<>();
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
if(root!=null)
queue.add(root);
else
return result;
while(!queue.isEmpty())
{
int count = queue.size();
double sum = 0;
for(int i = 0;i<count;i++)
{
TreeNode node = queue.poll();
sum+=node.val;
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
result.add(sum/count);
}
return result;
}
}
网友评论