# Binary Tree Level Order Traversal II

## Question

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).

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]
]


## 題解

### Java - Stack

/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/

public class Solution {
/**
* @param root: The root of binary tree.
* @return: buttom-up level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null) return result;

Stack<ArrayList<Integer>> s = new Stack<ArrayList<Integer>>();
q.offer(root);
while (!q.isEmpty()) {
int qLen = q.size();
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < qLen; i++) {
TreeNode node = q.poll();
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
s.push(aList);
}

while (!s.empty()) {
}
return result;
}
}


### Java - Reverse

/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/

public class Solution {
/**
* @param root: The root of binary tree.
* @return: buttom-up level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null) return result;

q.offer(root);
while (!q.isEmpty()) {
int qLen = q.size();
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < qLen; i++) {
TreeNode node = q.poll();
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
}

Collections.reverse(result);
return result;
}
}


### 源碼分析

Java 中 Queue 是接口，通常可用 LinkedList 實例化。