这道题比较简单,只是一个bfs,没什么要注意的,只是在存储数字的时候,记得把后面的数组放到最前面。我选用了linkedlist进行操作。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> result = new LinkedList<>();
if (root == null) {
return result;
}
LinkedList<TreeNode> q = new LinkedList<>();
List<Integer> val = new LinkedList<>();
q.add(root);
while (q.size() > 0) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode tmp = q.pollFirst();
if (tmp == null) {
continue;
}
val.add(tmp.val);
if (tmp.left != null) {
q.offer(tmp.left);
}
if (tmp.right != null) {
q.offer(tmp.right);
}
}
if (val != null) {
result.addFirst(val);
val = new LinkedList<>();
}
}
return result;
}
}