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;
}
}
本文介绍LeetCode 107题“二叉树的层次遍历II”的Java解法,通过广度优先搜索实现层次遍历,并利用双向链表收集每一层节点值,最后反转结果列表得到答案。

1338

被折叠的 条评论
为什么被折叠?



