原题链接在这里:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
与Binary Tree Level Order Traversal相似,只是返过来加链表。自然想到多用一个stack即可。像BFS用queue一层一层扫,出queue时添加到list里,用curCount计数,为0时表示当前level走完,list加到stack里,最后一个一个出栈。
Note: Queue<TreeNode>, Stack<List<Integer>>不要忘记加<>里的类型。
AC Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(root == null){
return res;
}
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(root);
Stack<List<Integer>> stk = new Stack<List<Integer>>();
int curCount = 1;
int nextCount = 0;
List<Integer> ls = new ArrayList<Integer>();
while(!que.isEmpty()){
TreeNode tn = que.poll();
curCount--;
ls.add(tn.val);
if(tn.left != null){
que.offer(tn.left);
nextCount++;
}
if(tn.right != null){
que.offer(tn.right);
nextCount++;
}
if(curCount == 0){
curCount = nextCount;
nextCount = 0;
stk.push(ls);
ls = new ArrayList<Integer>();
}
}
while(!stk.empty()){
res.add(stk.pop());
}
return res;
}
}