Leetcode 102.二叉树的层序遍历 Binary Tree Level Order Traversal(Java)
##Tree##, ##Breadth-first Search##
二叉树的层次遍历,需要借助队列
队列存储的是某一层的所有结点,统计当前层的结点个数count
,用count
次循环将该层所有结点计入解集合中,并按顺序将它们的左儿子和右儿子加入(下一层的所有结点)队列中
**时间复杂度:**O(n)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (root == null) return res;
queue.offer(root);
while (!queue.isEmpty()) {
LinkedList<Integer> path = new LinkedList<>();
int count = queue.size();
TreeNode t;
for (int i = 0; i < count; i ++) {
t = queue.poll();
path.add(t.val);
if (t.left != null) queue.offer(t.left);
if (t.right != null) queue.offer(t.right);
}
res.add(path);
}
return res;
}
}