107. 二叉树的层序遍历 II
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
Queue<TreeNode> que=new LinkedList<>();
if(root==null){
return res;
}
que.offer(root);
while(!que.isEmpty()){
int len=que.size();
List<Integer> temp=new LinkedList<>();
while(len>0){
TreeNode cur=que.poll();
temp.add(cur.val);
if(cur.left!=null){
que.offer(cur.left);
}
if(cur.right!=null){
que.offer(cur.right);
}
len--;
}
res.add(temp);
}
List<List<Integer>> result=new ArrayList<List<Integer>>();
for(int i=res.size()-1;i>=0;i--){
result.add(res.get(i));
}
return result;
}
}
就是在层序遍历的基础上,反转了一下
【补充】另外一种不用反转的写法
注意:addFirst方法是LinkedList中的,在声明返回数组时,声明的必须是:LinkedList< List< Integer>>,如果声明的是List< List< Integer>>会编译出错
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> res=new LinkedList<List<Integer>>();
Queue<TreeNode> que=new LinkedList<>();
if(root==null){
return res;
}
que.offer(root);
while(!que.isEmpty()){
int len=que.size();
List<Integer> temp=new LinkedList<>();
while(len>0){
TreeNode cur=que.poll();
temp.add(cur.val);
if(cur.left!=null){
que.offer(cur.left);
}
if(cur.right!=null){
que.offer(cur.right);
}
len--;
}
// res.add(temp);
res.addFirst(temp);
}
// List<List<Integer>> result=new ArrayList<List<Integer>>();
// for(int i=res.size()-1;i>=0;i--){
// result.add(res.get(i));
// }
// return result;
return res;
}
}
199. 二叉树的右视图
思路:就是在层次遍历到这一层的最后一个节点时,将他加入到结果数组中。最后一个结点的判断就是,这一层所在的队列长度为1时。
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list=new LinkedList<>();
Queue<TreeNode> que=new LinkedList<>();
if(root==null){
return list;
}
que.offer(root);
while(!que.isEmpty()){
int len=que.size();
while(len>0){
TreeNode cur=que.poll();
if(cur.left!=null){
que.offer(cur.left);
}
if(cur.right!=null){
que.offer(cur.right);
}
if(len==1){
list.add(cur.val);
}
len--;
}
}
return list;
}
}
注意:必须要有if(root==null)这个判断条件,否则直接执行que.offer(root)这个条件出队列的cur也是null,会报空指针异常。
637
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
List<Double> list=new LinkedList<>();
Queue<TreeNode> que=new LinkedList<>();
if(root==null){
return list;
}
que.offer(root);
while(!que.isEmpty()){
int len=que.size();
int length=len;
double num=0;
while(len>0){
TreeNode cur=que.poll();
num+=cur.val;
if(cur.left!=null){
que.offer(cur.left);
}
if(cur.right!=null){
que.offer(cur.right);
}
len--;
}
list.add(num/length);
}
return list;
}
}
如果不将num设置成double类型,最后的除法会是正数,将结果变为double类型才能进一步变成Double包装类,最简单的方法就是将num声明成double类型