二叉树的层序遍历
思路:队列
/**
* 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> res = new ArrayList<>();
Queue<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
double sum = 0.0;
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode t = q.poll();
sum += t.val;
if (t.left != null) q.offer(t.left);
if (t.right != null) q.offer(t.right);
}
res.add(sum / size);
}
return res;
}
}