1. 题目分析
一看这道题,我们就能想到按层遍历,一想到按层遍历,我们就想到了队列。
- 基本思想:用队列实现按层遍历
给出图解
2. 代码实现
2.1. Python代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
if root == None:
return None
queue = []
target = []
queue.append(root)
while len(queue) != 0:
size = len(queue)
sum = 0
for i in range(size):
node = queue.pop(0)
sum += node.val
if node.left != None:
queue.append(node.left)
if node.right != None:
queue.append(node.right)
target.append(float(sum)/size)
return target
2.2. 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) {
if(root == null){
return null;
}
Queue queue = new LinkedList();
List<Double> target = new ArrayList<>();
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
Double sum = 0d;
for(int i = 0;i < size;i++){
TreeNode node = (TreeNode)queue.poll();
sum += node.val;
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
target.add((Double)sum/size);
}
return target;
}
}