题目:从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
Reference:力扣(LeetCode),https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
解答:
/**
* 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) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> arr = new ArrayList<>();
queue.offer(root);
if (root == null){
return arr;
}
while(!queue.isEmpty()){
//记录每层的值得数组
ArrayList<Integer> level = new ArrayList<>();
//记录每层的节点个数
int num = queue.size();
//每个节点遍历
for (int i=0;i<num;i++){
TreeNode temp = queue.poll();
if (temp.left != null){
queue.offer(temp.left);
}
if (temp.right != null){
queue.offer(temp.right);
}
level.add(temp.val);
}
arr.add(level);
}
return arr;
}
}