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]
]
知识点
rrayList和LinkedList的区别有以下几点:
1. ArrayList是实现了基于动态数组的数据结构,而LinkedList是基于链表的数据结构;
2. 对于随机访问get和set,ArrayList要优于LinkedList,因为LinkedList要移动指针;
3. 对于添加和删除操作add和remove,一般大家都会说LinkedList要比ArrayList快,因为ArrayList要移动数据。但是实际情况并非这样,对于添加或删除,LinkedList和ArrayList并不能明确说明谁快谁慢
思路一
递归来加入每一层节点,每次循环清空list
思路二
运用queue先进先出的特性,依次pop出queue中的元素
由此题联想到后面107题107解析
反向层序遍历
/**
* 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) {
/*List<List<Integer>> res = new ArrayList<>();
List<TreeNode> list = new ArrayList<>();
if(root == null){
return res;
}
list.add(root);
while(!list.isEmpty()){
List<Integer> cur = new ArrayList<>();
List<TreeNode> next = new ArrayList<>();
for(TreeNode curNode:list){
cur.add(curNode.val);
if(curNode.left != null){
next.add(curNode.left);
}
if(curNode.right != null){
next.add(curNode.right);
}
}
list = next;
res.add(cur);
}
return res;
*/
//方法2 运用queue先进先出
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list =new ArrayList<>();
for(int i =0; i<size;i++){
TreeNode node =queue.pop();
list.add(node.val);
if(node.left!= null){
queue.offer(node.left);
}
if(node.right!= null){
queue.offer(node.right);
}
}
res.add(list);
}
return res;
}
}