问题描述
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 7return its bottom-up level order traversal as:
[
[15,7]
[9,20],
[3],
]confused what”{1,#,2,3}”means? > read more on how binary tree is serialized on OJ.
OJ’s Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘¥’ signifies a path terminator where no node exists below.
Here’s an example:
1
/
2 3
/
45
The above binary tree is serialized as”{1,2,3,¥,¥,4,¥,¥,5}”.
问题分析
这题考的是标准的二叉树层次遍历,用队列就可以解决了,要注意答案是要倒序输出,所以每次add到0的位置,把前面的层向后挤就行了
代码实现
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (queue.isEmpty() == false) {
ArrayList<Integer> list = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode curNode = queue.poll();
list.add(curNode.val);
if (curNode.left != null) queue.offer(curNode.left);
if (curNode.right != null) queue.offer(curNode.right);
}
result.add(0, list);
}
return result;
}