107. Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
就是复习以下树的分层遍历
我发现leetcode上基本上不用前序、中序、后序、分层遍历这些词,大多数都只有dfs和bfs
练习一下图和树的遍历,可以顺便把队列和栈之类的一起复习了
bfs用一个队列,而需要返回的列表用链表头插法就行了
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new LinkedList<>();
if(root==null){
return list;
}
list.add(new ArrayList<Integer>(){{add(root.val);}});
Queue<TreeNode> que = new ArrayDeque<>();
que.add(root);
while(!que.isEmpty()){
Queue<TreeNode> subque = new ArrayDeque<>();
List<Integer> sublist=new ArrayList();
while(!que.isEmpty()){
TreeNode tmp = que.remove();
if(tmp.left!=null){
sublist.add(tmp.left.val);
subque.add(tmp.left);
}
if(tmp.right!=null){
sublist.add(tmp.right.val);
subque.add(tmp.right);
}
}
if(sublist.size()!=0){
list.add(0,sublist);
que.addAll(subque);
}
}
return list;
}
}
代码写的啰嗦了,多用了好多空间,当反例用了
改进点:
- 用指针来做队列的头和尾,就不需要这么麻烦再建一个子队列
- 出队列读取和进队列读取的问题,进队列读取时的好处是能分出同一个结点的支,这题用不到,用出队列读取能统一流程(头结点)
- 单端队列用LinkedList就可以,没必要使用Deque
改进的代码:
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> list = new LinkedList<>();
if(root==null) return list;
Queue<TreeNode> que = new LinkedList<TreeNode>(){{add(root);}};
while(!que.isEmpty()){
int size = que.size();
List<Integer> sublist=new ArrayList<>();
for(int i=0;i<size;++i){
TreeNode tmp = que.remove();
if(tmp.left!=null) que.add(tmp.left);
if(tmp.right!=null) que.add(tmp.right);
sublist.add(tmp.val);
}
list.add(0,sublist);
}
return list;
}
}