BinaryTreeLevelOrderTraversalII [source code]
public class BinaryTreeLevelOrderTraversalII {
static
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Deque<List<Integer>> levels = new ArrayDeque<>();
List<Integer> level = new ArrayList<>(Arrays.asList(root.val));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
level = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
levels.push(level);
}
res.addAll(levels);
return res;
}
}
public static void main(String[] args) {
BinaryTreeLevelOrderTraversalII.Solution tester = new BinaryTreeLevelOrderTraversalII.Solution();
}
}
虽然其实是一个比较基础的题目, 但是 BFS 还真是第一次写, 有些细节确实是第一次碰到和琢磨;
LinkedList as Queue, not ArrayList
这个也是一个小盲点;
BFS操作的核心就是每一个 iteration 解决一个 level; 可以说有一个invariant就是there are never nodes belonging to more than one levels in the queue at the same time;
inner header 的写法:
for (int i = 0; i < size; i++) {
不能直接用 queue.size(), 因为每一个 iteration, queue 的 size 都是实时变化的. size 这里存的其实是当前 iteration 正在处理的 level 的 size;
最后的速度是3(25), 不算好;
Problem Description
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,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
Difficulty:Easy
Category:Algorithms
Acceptance:39.62%
Contributor: LeetCode
Related Topics
tree breadth-first search
Similar Questions
Binary Tree Level Order Traversal