题目
题链:剑指 Offer 32 - II. 从上到下打印二叉树 II
题解
广度优先遍历、加一个循环分层。
大佬详细题解:剑指 Offer 32 - II. 从上到下打印二叉树 II
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null){
return new ArrayList<>();
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
List<List<Integer>> res = new ArrayList<>();
while (!queue.isEmpty()){
List<Integer> ans = new ArrayList<>();
for (int i = queue.size(); i >0; i--) {
TreeNode node = queue.poll();
if (node.left != null){
queue.offer(node.left);
}
if (node.right != null){
queue.offer(node.right);
}
ans.add(node.val);
}
res.add(ans);
}
return res;
}
}