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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<List<Integer>> mLists = new ArrayList<List<Integer>>();
private Queue<TreeNode> q = new LinkedList<TreeNode>();
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root == null){
return mLists;
}
q.offer(root);
int curNum = 1;
int nextNum = 0;
while(curNum>0){
List<Integer> list = new ArrayList<Integer>();
while(curNum>0){
curNum--;
if(q.peek().left != null){
q.offer(q.peek().left);
nextNum++;
}
if(q.peek().right != null){
q.offer(q.peek().right);
nextNum++;
}
list.add(q.poll().val);
}
mLists.add(list);
curNum = nextNum;
nextNum = 0;
}
Collections.reverse(mLists);
return mLists;
}
}