剑指 Offer 32 - II. 从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树:[3,9,20,null,null,15,7],
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
解题思路
广度优先遍历
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) return new LinkedList<>();
Queue<TreeNode> level = new LinkedList<>();
List<List<Integer>> res = new LinkedList<>();
level.add(root);
while (!level.isEmpty()) {
int levelSize = level.size();
LinkedList<Integer> temp = new LinkedList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode tempTree = level.poll();
if (tempTree.left != null) level.add(tempTree.left);
if (tempTree.right != null) level.add(tempTree.right);
temp.add(tempTree.val);
}
res.add(temp);
}
return res;
}
}