上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
}
};
python3 解法, 执行用时: 156 ms, 内存消耗: N/A, 提交时间: 2018-08-27 16:11:05
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
from queue import Queue
vec = []
if root == None:
return vec
q = Queue()
q.put(root)
while q.empty() != True:
number = q.qsize()
s = 0
for i in range(0, number):
temp = q.get()
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
s += temp.val
vec.append(s / number)
return vec
java 解法, 执行用时: 8 ms, 内存消耗: N/A, 提交时间: 2018-08-27 15:09:12
/**
* 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) {
List<Double> vec = new ArrayList<Double>();
java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>();
queue.offer(root); //队尾插入元素
while ( queue.peek() != null ) { //队首不为空
long sum = 0;
int number = queue.size();
for(int i = 0; i < number; i++) {
TreeNode temp = queue.poll(); //弹出队首元素
if(temp.left != null) {
queue.offer(temp.left);
}
if(temp.right != null) {
queue.offer(temp.right);
}
sum += temp.val;
}
vec.add((double)sum / number);
}
return vec;
}
}
cpp 解法, 执行用时: 16 ms, 内存消耗: N/A, 提交时间: 2018-08-27 14:35:29
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> vec;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
long sum = 0;
int number = que.size();
for(int i = 0; i < number; i++) {
TreeNode* temp = que.front();
que.pop();
if(temp->left != NULL) {
que.push(temp->left);
}
if(temp->right != NULL) {
que.push(temp->right);
}
sum += temp->val;
}
vec.push_back((double)sum / number);
}
return vec;
}
};