Leetcode107.二叉树的层次遍历II Binary Tree Level Order Traversal II(Java)
##Tree##, ##Breadth-first Search##
和102.二叉树的层次遍历做法大致相同
不同部分在于对最终的结果List<List<Integer>> res
需要使用Collections.reverse()
反转一下得到最终结果
**时间复杂度:**O(n)
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root == null) return res;
q.add(root);
while (!q.isEmpty()) {
int count = q.size();
LinkedList<Integer> path = new LinkedList<>();
for (int i = 0; i < count; i ++) {
TreeNode curr = q.poll();
path.add(curr.val);
if (curr.left != null) q.add(curr.left);
if (curr.right != null) q.add(curr.right);
}
res.add(path);
}
Collections.reverse(res);
return res;
}
}