Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
分析
这题与107. Binary Tree Level Order Traversal II一样,都是二叉树的层序遍历,区别是102是从顶至底,107是从底至顶。
借助队列用BFS即可,核心思想是记录每一层中有几个元素(n),元素出队时把孩子节点入队,出队的元素放入临时数组,出够n个以后,临时数组中的值就是当前level的元素,把临时数组放入结果数组。对于102,临时数组放入结果数组的末尾,对于107,需要把临时数组放入结果数组的开头,因此对于结果数组而言,使用LinkedList更好。
code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> tmp = new ArrayList<>();
int n = queue.size();
while (n > 0) {
TreeNode node = queue.poll();
tmp.add(node.val);
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
n--;
}
res.add(tmp);
// res.add(0, tmp); // for 107
}
return res;
}
}