We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
思路:
class Solution { public List<Double> averageOfLevels(TreeNode root) { Queue<TreeNode> que = new LinkedList<>(); //判断空 if (root != null) { que.offer(root); } List<Double> list = new ArrayList<>(); while (!que.isEmpty()) { int len = que.size(); double sum = 0.0; for (int i = 0; i < len; i++) {//这里不能用while判断 会改变len的值 TreeNode node = que.poll();//弹出并临时记录 sum += node.val;//求和 //将该层的平均值存放到一维数组中 if (node.left != null) { que.add(node.left); } if (node.right != null) { que.add(node.right); } } list.add(sum / len); } return list; } }
注意:这里不能用while
不能用 while(len > 0) { ... len--; } 因为len改变了,就无法计算sum/len了,这点要注意
The text was updated successfully, but these errors were encountered:
No branches or pull requests
637. 二叉树的层平均值
思路:
The text was updated successfully, but these errors were encountered: