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).
Approach 1: Using a stack
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null) return result;
Stack<ArrayList<Integer>> s = new Stack<ArrayList<Integer>>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while (!q.isEmpty()) {
ArrayList<Integer> level = new ArrayList<Integer>();
for (int i = 0; i < q.szie(); i++) {
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
s.push(level);
}
while (!s.empty()) {
result.add(s.pop());
}
// Or adopt the approch of Collections.reverse(result);
return result;
}
}