力扣 LeetCode 102. 二叉树的层序遍历(Day6:二叉树)
解题思路:
使用队列
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Deque<TreeNode> queue = new ArrayDeque<>();
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.add(list);
}
return res;
}
}